The array length
property sets or returns the number of elements in an array. It represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
var items = ['shoes', 'shirts', 'socks', 'sweaters']; items.length; // returns 4
The value of the length
property is an integer with a positive sign and a value less than 2 to the 32nd power (232).
You can set the length
property to truncate an array at any time. When you extend an array by changing its length
property, the number of actual elements does not increase; for example, if you set length
to 3 when it is currently 2, the array still contains only 2 elements. Thus, the length
property does not necessarily indicate the number of defined values in the array. See also Relationship between length
and numerical properties.
Property attributes of Array.length
| |
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
In the following example, the array numbers
is iterated through by looking at the length
property. The value in each element is then doubled.
var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] *= 2; } // numbers is now [2, 4, 6, 8, 10]
The following example shortens the array numbers
to a length of 3 if the current length is greater than 3.
var numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3
Specification | Status | Comment |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
ECMAScript 5.1 (ECMA-262) The definition of 'Array.length' in that specification. | Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.length' in that specification. | Standard | |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Array.length' in that specification. | Draft |
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length