Arrays are a vital building block for any program, even simple ones. An array is a container that holds any number of other values or objects. So it’s a list of things.
Each item stored in an array has an index which indicates that item’s position in the array. These indexes are numerical – counting starts at 0 for the first item in the array.
Here’s an array containing some trees:
var trees = ['pine', 'birch', 'spruce'];
pine is the first item in the array, at index 0. birch is the second item in the array at index 1, and so on.
The length Property of Arrays
To find the length (number of items in) an array, simply use the length property of the array:
trees.length //Returns 3
Simply access the length property of your array variable, and the number of items will be returned as an integer value.
Truncating / Setting the Length
The length property has one other trick up its sleeve – it can be used to set the length of an array as well as reading it.
This will cut off all items in the array past the given length:
trees.length = 2; console.log(trees) // ['pine', 'birch'] trees.length; // Now returns 2
Above, the length property of the trees array is set to 2. As it was previously 3, the last item in the array (the spruce value) is deleted to make the array the given length of 2.
When the length property is reaccessed, it now reads the new value of 2.