How To Get The Length Of An Array In JavaScript

How to get the length of an array in JavaScript

After this lesson, you will learn how to get the length of an array in JavaScript with the length property. Let’s go into detail.

Get the length of an array in JavaScript

Using array.length with elements have been assigned values

The Javascript array length is the number of elements in the Javascript array, including both empty and assigned elements.

To find the array length in Javascript we can use the length property with the following syntax:

array.length

array is the initial array to find the length, length in Javascript is a property used to find the length or number of elements of an object in Javascript. If this object is an array, the length property will return the value equal to the last index + 1 unit.

Sample

let arr1 = ["one", "two", "three"];
console.log(arr1.length);
 
let arr2 = [1, 2, 3, 4, 5];
console.log(arr2.length);
 
let arr3 = [9, ["five, six"], 1, 8];
console.log(arr3.length);

Output

3
5
4

Note that array.length will be calculated including both assigned elements and empty elements in the array.

Using array.length with empty elements in the array

For example, we have 5 elements in the below array. Although only 2 elements are used, the array’s length is not the number of elements used to assign the result but the total number of elements included. All empty elements are as follows:

let arr = new Array(5);
arr[0] = 2;
arr[1] = 8;
 
// Display the length of the array
console.log(arr.length);

// Display the elements in the array
console.log(arr);

Output

5
[2, 8, null, null, null]

array.length has three properties: Writable, configurable, and enumerable.

  • Writeable: By default, this property is set to true. By changing it to false, this property does not allow further modification to the length property.
  • Configurable: This property is set to false by default. We cannot remove the property or change any more properties.
  • Enumerable:  By default, this property is set to false. If it is changed to true, then array.length will be iterated through the for or for...in loop.

Summary

Above, I’ve shown you how to get the length of an array in JavaScript by using array.length property. I hope they are useful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *