Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What internal method is calling in javascript when I get array element value by index?

Tags:

javascript

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.

like image 718
Pinal Avatar asked Mar 21 '23 12:03

Pinal


1 Answers

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.

like image 122
James Allardice Avatar answered Apr 25 '23 05:04

James Allardice