Two solutions I can think of. Both require some modification to your interactions with the array.
First solution
Keep a counter.
If you simply keep a counter that represents how many elements in the array are actually there, then the emptiness check is a mere comparison.
var n = 0;
// Adding something to the array:
myArr[2] = somethingDefined;
n ++;
// Removing from the array:
delete myArr[2];
n --;
// Check if empty
if(n == 0) {
console.log("myArr is empty.");
}
Second solution
Use splice
instead of delete
splice
will actually modify the array instead of setting the values to undefined
. Example:
myArr.splice(2, 1); // Get rid of myArr[2]
And this mutates the array and will change .length
so you can easily check the actual length of the array. Note that splice
is less efficient (and given you seem to care about the efficiency, the first solution is probably more applicable).