techStackGuru

JavaScript Array length method


An arrays length attribute is an unsigned 32-bit integer that is always numerically higher than the arrays largest index. The length property may be used to remove elements from an array or to make it empty.


Syntax


array.length

Example


const alphabets = [ 'A', 'B', 'C', 'D' ];
console.log(alphabets.length); // 4

The colors array has a length of zero when it is empty


const alphabets = [];
console.log(alphabets.length); // 0

Sparse arrays

The items of a sparse array do not have contiguous indexes starting at zero.


const alphabets = [ 'A', , 'C', 'D' ];
console.log(alphabets.length); // 4

Empty arrays

The array will be empty if length is set to zero


const alphabets = [ 'A', 'B' , 'C', 'D' ];
console.log(alphabets); // [ 'A', 'B', 'C', 'D' ]

alphabets.length = 0;
console.log(alphabets); // []

Remove arrays

If you set length to 2, then the array will remove the remaining elements from the array:


const alphabets = [ 'A', 'B' , 'C', 'D' ];
alphabets.length = 2;

console.log(alphabets); // [ 'A', 'B' ]