How to get the Length of an Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20211 min read

Get the Length of an Array in JavaScript #

To get the length of an array, use the length property. For example, ['a', 'b'].length returns 2. The length property sets or returns the number of elements in the array. When accessed on an empty array, the length property returns 0.

index.js
const arr = ['a', 'b', 'c']; console.log(arr.length); // ๐Ÿ‘‰๏ธ 3 console.log([].length); // ๐Ÿ‘‰๏ธ 0

In the examples, we use the Array.length property to get the number of elements the array contains.

The length property always returns an integer with a positive sign.

The property can also be set by the user.

Here are examples of truncating an array by setting it's length property to a lower value.

index.js
const arr = ['a', 'b', 'c']; arr.length = 1; console.log(arr); // ๐Ÿ‘‰๏ธ ['a'] arr.length = 0; console.log(arr); // ๐Ÿ‘‰๏ธ []

After setting the array's length to 1, only the first element remained in the array.

Setting an array's length property to 0 empties the array.

And here is an example of setting an array's length to a higher value.

index.js
const arr = ['a']; arr.length = 3; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', , ] console.log(arr.length); // ๐Ÿ‘‰๏ธ 3

After we set the array's length to a higher value, the array got filled with empty elements.

All of the empty elements in the array are non-iterable.

It's extremely rare and considered a bad practice to see programmers change the array's length value.

That's because there are specialized methods that allow us to manipulate an array, that work in a more predictable manner.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee