Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.length

The number of elements in an array.

Available since: ES1

Syntax

array.length

Return 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:

3

The last element and an emptiness check:

const fruits = ['apple', 'pear', 'plum'];
 
console.log(fruits[fruits.length - 1]);
console.log([].length === 0);

Output:

plum
true

Assigning 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

In the tutorial

  • Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.

Thanks for reading!

Donate to the site — we work hard for you.