Arrays are objects. That means that your array
[undefined,undefined,undefined,empty,4]
could be written as such an object:
{
0: undefined,
1: undefined,
2: undefined,
// 3 doesnt exist at all
4: 4,
length: 5,
}
So undefined
is actually a slot that exists and holds a value while 3
is not even a key-value pair. As accessing a non existing key results in undefined
there is no real world difference:
array[2] // undefined
array[3] // undefined
But iterating over an array with map
and others will skip empty ones, so then you should use .fill
before iterating.
The only way to detect a difference is to check if the key exists:
2 in array // true
3 in array // false
To turn empty
to undefined
you could set the key:
array[3] = undefined;
and to turn undefined
into empty
you have to remove the key:
delete array[3]
however that rarely matters.