Isaac
Isaac

Reputation: 12874

Can array.length be trusted?

let arr = [];
arr[3] = undefined;
console.log('length: ',arr.length);

if(arr.length === 0){
  //I wanted to come here
}else{
  //But instead coming here
  console.log('>>',arr[0]);
  console.log('>>',arr[3]);
}

I've just noticed that if we're not using a push function to insert item into an array, the length will be updated, even if we assigning undefined. Clearly, the arr showing above is simply nothing inside.

During a conditional checking, how can we really sure that an array is empty? I can only think of manually looping thru the array and doing a count++ which looks really redundant.

Upvotes: 2

Views: 115

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Array.length:

The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

When you assign undefined to an index of an array, that index becomes an existing property on said array. But, like any variable, it can have anything assigned to it, including null and undefined.

If you ever run into situations like this (which you shouldn't - sparse arrays are a terrible idea), you can check the keys or the keys and values of the array:

const arr = [];
arr[3] = undefined;
console.log(Object.keys(arr)); // Not empty!

const allArrElmsAreUndefined = arr => Object.values(arr).every(item => item === undefined);
console.log(allArrElmsAreUndefined(arr));

Upvotes: 5

Related Questions