JavaScript Array Length Property: Getting & Setting
With JavaScript, you're not only limited to retrieving the length of an array, but you can also manipulate the array's data by changing its length programmatically.
This article will teach you how to get and set an array length in JavaScript.
What is the JavaScript.Array length
Property?
length
is a property of the JavaScript.Array
class and allows you to return or assign the number of elements within a given array. Array elements could include strings, integers, objects, additional arrays, and more.
The length
property is a positive integer up to a maximum of 2 to the 32nd power, or 232, in value.
Getting Array Length
Here's an example illustrating how to retrieve an array length in JavaScript:
var colors = ["Red", "Green", "Blue", "Purple"];
console.log(colors);
// 4
There are four elements, so the resulting output is 4.
Setting Array Length
You can also set an array length in JavaScript by altering an array's contents. By setting the length of the array to a smaller value than that of the actual length, you're truncating the excess elements from the end of the array.
Let's assume you have the same four colors as above, but you set the length to a smaller value than that of the total array length:
var colors = ["Red", "Green", "Blue", "Purple"];
colors.length = 2;
console.log(colors);
// ["Red", "Green"]
Out of curiosity, I checked to see what would happen if you set the length of the array larger than its actual length and came up with the following result:
var colors = ["Red", "Green", "Blue", "Purple"];
colors.length = 10;
console.log(colors);
// ["Red", "Green", "Blue", "Purple", empty x 6]
The remaining six elements in the array don't return as null or even as array nodes themselves, just empty elements.
You can also empty an array completely by setting its length to 0:
var colors = ["Red", "Green", "Blue", "Purple"];
colors.length = 0;
console.log(colors);
// []
Property Attributes Available
There are three properties available for the JavaScript.Array length
property:
- Writeable: A value of true indicates the value of the property can be changed, while a value of false indicates that the value cannot be changed.
- Configurable: If this attributes is set to false, attempts to change or delete any of the three property's attributes will fail.
- Enumerable: Setting this attribute to a value of true allows the property to be iterated over during a
for
orfor..in
loop.
Conclusion
The JavaScript.Array length
property allows you to get an array's length as well as set the length by truncating or appending additional elements as necessary, and is supported by all browsers.
There are additional JavaScript array manipulation functions available that allow you to manipulate data within an array, also affecting its length.
Comments
There are no comments yet. Start the conversation!