I have some wtfjs
code:
var a = [,];
alert(a.indexOf(a[0]));
a.indexOf(a[0])
returns -1
. The main point in this example is difference between uninitialized
and undefined
values:
a
contains one not initialized element.
a[0]
return undefined
.
a
don't contains the undefined
value. So a.indexOf(a[0]) === -1
is true
.
But where I can find the explanation why a[0]
return undefined
? What internal method is calling?
P.S. Undefined
is the javascript primitive type. Uninitialized
means the value that don't have any javascript type, but there is no such primitive type in javascript.
The ES5 spec tells us the following of array initialisers:
Elided array elements are not defined.
Note that they are not defined. That's different from having the value undefined
. As you've already noticed, elided elements do contribute to the length of the array:
...the missing array element contributes to the length of the Array and increases the index of subsequent elements.
When you invoke indexOf
on an array this is one of the steps that happens:
Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument ToString(k).
In that, k
is a number corresponding to an array index and O
is the array itself. Since elided elements were not defined the array does not have a property for the corresponding index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With