Array.length
The Array.length
property in JavaScript represents the number of elements in an array. It is a read/write property that can be used to retrieve or set the size of an array.
Syntax
array.length
Value
A nonnegative integer less than 232
that specifies the number of elements in the array.
Property Attributes
Attribute | Value |
---|---|
Writable | Yes |
Enumerable | No |
Configurable | No |
Return Value
The length
property returns the number of elements in the array. Modifying this property can resize the array, truncating elements if the new length is smaller.
Examples
1. Retrieving the Length of an Array
In this example, the length
property is used to retrieve the number of elements in an array.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.length);
Output
3
The length
property returns the number of elements in the fruits
array.
2. Modifying the Length of an Array
The length
property can be set to resize the array. If the new length is smaller than the current length, the array is truncated, and elements beyond the new length are removed.
const numbers = [1, 2, 3, 4, 5];
// Reduce the length of the array
numbers.length = 3;
console.log(numbers);
// Extend the length of the array
numbers.length = 6;
console.log(numbers);
Output
[ 1, 2, 3 ]
[ 1, 2, 3, <3 empty items> ]
- When the length is reduced to
3
, elements4
and5
are removed from the array. - When the length is increased to
6
, new empty slots are added, which are undefined.
3. Using length
to Empty an Array
Setting the length
property to 0
clears all elements from the array.
const items = [1, 2, 3, 4, 5];
items.length = 0;
console.log(items);
Output
[]
The array is now empty because its length
was set to 0
.
4. Using length
to Iterate Over an Array
The length
property is commonly used in loops to iterate through all elements of an array.
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Output
red
green
blue
The loop iterates through the array using the length
property to determine the number of elements.