var a = [undefined, undefined];
var b = new Array(2);
0 in a // returns true
1 in a // returns true
0 in b // returns false
1 in b // returns false
Can anyone explain to me why this is happening?
var a = [undefined, undefined];
var b = new Array(2);
0 in a // returns true
1 in a // returns true
0 in b // returns false
1 in b // returns false
Can anyone explain to me why this is happening?
b = new Array(2);
just says that, b
is an array of size two. But the array is just empty. It doesn't have any elements in it. So, there are no indexes as such. So, 0
and 1
are not yet there in b
. These are called holes.
But, when you say
var a = [undefined, undefined];
you are creating an array with two elements in it. So, it has undefined
at index 0
and 1
. That is why they both exist in the array.
Note: When you simply assign a value to a variable, without declaring it with var
(let
or const
), it will become a global variable.