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

</>
Copy
array.length

Value

A nonnegative integer less than 232 that specifies the number of elements in the array.

Property Attributes

AttributeValue
WritableYes
EnumerableNo
ConfigurableNo

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.

</>
Copy
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.

</>
Copy
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> ]
  1. When the length is reduced to 3, elements 4 and 5 are removed from the array.
  2. 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.

</>
Copy
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.

</>
Copy
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.