Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const items = ["a", "b", "c"];
items.length;     // 3
items.length = 1; // items is now ["a"]

Try it

JS Reading and writing length

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Length is not the element count

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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] = 1 on an empty array makes length 101, although only one element exists. Sparse arrays therefore report a larger length than the number of actual elements.
  • Truncation deletes data. Elements at indexes >= newLength are 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 arr is false for them, forEach() skips them, and Object.keys() leaves them out. Use fill() or Array.from({ length: n }) when you need real values.
  • Clearing in place. arr.length = 0 empties 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 change length.
  • The Array(n) constructor. new Array(3) makes an array of length 3 with empty slots, but new Array("3") makes an array with one element. A fractional or negative number throws a RangeError.
  • Reading is cheap. length is 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.