JavaScript Reference ยท Array
Array.prototype.length
Reference for the JavaScript Array length property: how it counts elements, why it is writable, how setting it truncates or extends an array, and its limits.
The length property of an array is a non-negative integer that is always one more than the highest index in use. For a normal array that is simply the number of elements. It updates automatically when you add or remove elements.
Unlike the length of a string, an array's length is writable. Assigning a smaller number cuts off the elements beyond it; assigning a larger number makes the array longer with empty slots.
const items = ["a", "b", "c"]; items.length; // 3 items.length = 1; // items is now ["a"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.length array.length = newLength
Value: an integer from 0 to 2^32 - 1 (4,294,967,295).
Exceptions: assigning a value that is not a valid length (negative, fractional, NaN, or larger than 2^32 - 1) throws a RangeError. Assigning to the length of a frozen array, or a non-writable length, throws a TypeError in strict code.
Usage notes
- Highest index plus one, not a count.
arr[100] = 1on an empty array makeslength101, although only one element exists. Sparse arrays therefore report a largerlengththan the number of actual elements. - Truncation deletes data. Elements at indexes
>= newLengthare removed and cannot be restored by setting the length back; the slots come back empty. - Extending adds holes, not
undefined. The new slots are empty:i in arrisfalsefor them,forEach()skips them, andObject.keys()leaves them out. Usefill()orArray.from({ length: n })when you need real values. - Clearing in place.
arr.length = 0empties the array while keeping the same object, which matters if other variables reference it.arr = []creates a new array instead. - Non-index properties don't count. Adding
arr.name = "x"does not changelength. - The
Array(n)constructor.new Array(3)makes an array of length 3 with empty slots, butnew Array("3")makes an array with one element. A fractional or negative number throws aRangeError. - Reading is cheap.
lengthis a stored property, so reading it in a loop condition is fine in modern engines. - Strings and typed arrays have a read-only
length; only plain arrays let you set it.
Browser support
length is a core feature of arrays and works in every browser and JavaScript engine.