codewithjohn.dev
Published on

The Length Property in JavaScript Arrays

Sometimes You’ll want to know how many values are in the array, or simply the length of the array. The JavaScript array length property property sets or returns the number of elements in the array.

JavaScript The length property is always one higher than the highest index value in the array because of the Javascript index Values start at 0.

To find the length of an array, reference the object array. length. The length property returns an integer. If we access an empty array, the length property returns 0.

Here is an example: we use the Array.length property to get the number of elements the array contains.

example_one.js
const arr = ['a', 'b', 'c'];

console.log(arr.length); // 👉️ 3

console.log([].length); // 👉️ 0

Here is another example of truncating an array by setting its length property to a lower value.

example_two.js
const arr = ['a', 'b', 'c'];

arr.length = 1;

console.log(arr); // 👉️ ['a']

arr.length = 0;

console.log(arr); // 👉️ []

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

We can also set the length property to a higher value. Then the array got filled with empty elements.

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

example_three.js
const arr = ['a'];

arr.length = 3;

console.log(arr); // 👉️ ['a', empty × 2]

console.log(arr.length); // 👉️ 3

Conclusion

In This article, we discussed how to use the length property to retrieve the number of items in a JavaScript array. We also walked through two examples of the length. property. After reading this tutorial, you are ready to Start using the length property like an expert!