The JavaScript Array.length property is a fundamental and widely used property that returns or sets the number of elements in an array. It is a non-writable property that can also be used to truncate or expand the array.
Syntax
array.length
Return Value
Value | Description |
---|---|
Number | The length property returns a number representing the number of elements in the array. |
Example 1: Getting the Length of an Array
This example demonstrates how to use the length property to get the number of elements in an array.
let arr = [1, 2, 3, 4, 5]; console.log(arr.length); // Output: 5
Example 2: Setting the Length of an Array
This example shows how to set the length property to truncate an array.
let arr = [1, 2, 3, 4, 5]; arr.length = 3; console.log(arr); // Output: [1, 2, 3] console.log(arr.length); // Output: 3
Example 3: Expanding an Array Using the Length Property
This example demonstrates how to use the length
property to expand an array. The new elements will be undefined
.
let arr = [1, 2, 3]; arr.length = 5; console.log(arr); // Output: [1, 2, 3, undefined, undefined] console.log(arr.length); // Output: 5
Example 4: Using Length Property in a Loop
This example shows how to use the length property in a loop to iterate over the elements of an array.
let arr = ['a', 'b', 'c', 'd']; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // Output: // 'a' // 'b' // 'c' // 'd'
Example 5: Automatic Update of Length Property
The length property automatically updates when new elements are added to the array.
let arr = [1, 2, 3]; arr.push(4); console.log(arr.length); // Output: 4 arr[10] = 11; console.log(arr.length); // Output: 11 console.log(arr); // Output: [1, 2, 3, 4, empty × 6, 11]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |