Array.prototype.length
The number of elements in an array.
Available since: ES1
Syntax
array.lengthReturn value
numberThe number of elements (the index of the last element plus one).
Examples
The length of an array:
const fruits = ['apple', 'pear', 'plum'];
console.log(fruits.length);Output:
3The last element and an emptiness check:
const fruits = ['apple', 'pear', 'plum'];
console.log(fruits[fruits.length - 1]);
console.log([].length === 0);Output:
plum
trueAssigning to length truncates the array:
const numbers = [1, 2, 3, 4, 5];
numbers.length = 2;
console.log(numbers);Output:
[
1,
2
]Notes
Indexes start at zero, so the last element has the index length - 1. A shorter way to get it is at(-1).
See also
- Array.prototype.push — Appends elements to the end of an array.
- Array.prototype.at — Returns the element at an index; negative indexes are allowed.
- String.prototype.length — The length of a string — how many characters it has.
In the tutorial
- Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.