The Array.length
property is a built-in property representing the number of elements in an array. It is a dynamic property that updates automatically whenever elements are added or removed from the array.
Syntax
array.length
Return Value
The length
property returns a non-negative integer that specifies the number of elements in the array.
Example 1: Getting the Length of an Array
let arr = [10, 20, 30, 40, 50]; console.log(arr.length); // Output: 5
Example 2: Using length
in a Loop
let arr = [10, 20, 30, 40, 50]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // Output: // 1 // 2 // 3 // 4 // 5
Example 3: Dynamically Updating the Array Length
let arr = [10, 20, 30, 40, 50]; arr.length = 3; console.log(arr); // Output: [10, 20, 30] console.log(arr.length); // Output: 3
Setting the length
property to a smaller value truncates the array, removing elements beyond the specified length.
Example 4: Expanding the Array Length
let arr = [10, 20, 30]; arr.length = 5; console.log(arr); // Output: [10, 20, <3 empty items>] console.log(arr.length); // Output: 5
When the length
property is set to a value greater than the current array size, new slots are added as empty items.
Example 5: Modifying length
to Clear an Array
let arr = [10, 20, 30, 40, 50]; arr.length = 0; console.log(arr); // Output: [] console.log(arr.length); // Output: 0
Example 6: Adding Elements Beyond Current Length
let arr = [10, 20, 30]; arr[5] = 60; console.log(arr); // Output: [10, 20, 30, <2 empty items>, 60] console.log(arr.length); // Output: 6
Adding an element at an index beyond the current length automatically adjusts the length
property.
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |