When it comes to arrays, their length is not simply determined by the number of elements in them. Instead, the length of an array is based on the maximum index present in that array, especially for sparse arrays.
For instance:
let a = [];
a[10] = 1;
console.log(a.length);
console.log(a);
In this case, the length of array 'a' is 11 (ranging from index 0 to 10), even though there are instances where some indices have values of undefined
.
Interestingly, setting the last value to undefined
doesn't impact the length as long as there is still a reference to undefined
in that position.
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
a[10] = undefined
console.log(a.length);
Even using the delete method to remove elements won't alter the array's length property.
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
delete a[10];
console.log(a.length);
The only way to truly change the length of an array is by creating a new array containing a subset of the original one:
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
console.log(a);
a = a.slice(0,9);
console.log(a.length);
console.log(a);