What is Array.length

А large number of elements in the code array could be a headache for any programmer. The length property comes to help. It is a 32-bit infinite number that is greater than the highest index in the array.

Its formula can be represented as "highest index + 1". Its maximum value is 232, which is 4294967296 - this is the limited number of elements in the length property we plan to work with. You can use it to modify an array anywhere in the code.

First of all, the length values are used to determine the number of elements in a given array. Changing the number of items in the length bar will also change automatically and display new data.

var arr = [];
alert(arr.length);   // 0
   
arr[0] = 23;
alert(arr.length);   // 1
  
arr[1] = 13;
alert(arr.length);   // 2

The length property is most often used to adjust the number of elements in an array - both to add and remove elements from it.

There are 2 types of arrays:

  • dense arrays - where all values are contiguous and must start from zero (with length you can determine the exact number of elements) in a given array.

  • sparse arrays - where values do not have to be contiguous, yet the array starts from zero. May contain elements that are displayed as "undefined".

Practical use

In JavaScript, you can perform a large number of tasks by changing the length property - changing the number of elements in arrays of different types, and modifying their type if necessary. So with the help of such manipulations you can remove or add elements, turn the array into a sparse.

  • Empty an array

If you set the length property to zero, the array will be empty. The length index is crucial in the array and it is more important than the number of elements in it.

const animals = ['elephant', 'tiger', 'giraffe'];
animals.length = 0;
  
console.log(animals); // [  ]
  • Remove elements

If you set the length property to an index lower than the highest index or the number of elements in an array type, elements whose index is higher than or equal to the new one are automatically deleted.

For example, if you set the length of 2 in the animals array with 3 elements, the last element will be automatically deleted.

const animals = ['elephant', 'tiger', 'giraffe'];
animals.length = 2;
 
console.log(animals); // ['elephant', 'tiger']
  • Make array sparse

If, on the contrary, the value of length exceeds the number of elements in the array, then in the code the array becomes sparse.

So in the animals array, in which there are only 3 elements, we set the index 5, which is 2 units higher than the original value, and in the code, these new elements must be displayed.

const animals = ['elephant', 'tiger', 'giraffe'];
animals.length = 5;
console.log(animals); // ['elephant', 'tiger', 'giraffe', <2 empty items>]

Because empty items without a specified value are not displayed, they are replaced by "2 empty items" in the array. As a result, it turns the array into a sparse one.