Skip to content Skip to sidebar Skip to footer

What Does [undefined × 2] Mean And Why Is It Different To [undefined,undefined]?

While answering this question ( Difference between [Object, Object] and Array(2) ) I happened across something in JavaScript arrays that I wasn't previously aware of (ironic, consi

Solution 1:

What does undefined × 2 mean?

Consoles display what some developer has decided is a useful message based on some input. It should not be regarded as normative in any sense, and in some cases is misleading. The statement:

var x = Array(2);

Creates a variable x and assigns a new array with length 2. There are no "empty slots" in any meaningful sense. It is equivalent to:

var x = [,,];

(noting that old IE had a bug where the above created an array with length 3 not 2). You can think of it as an object like:

var x = {length: 2};

The number of properties that can be added is in no way limited by setting the length. However setting the length of an existing array will delete any members with indexes equal to or higher than the new length.

Having said that, implementations are free to allocate space for "length" worth of indexes, which seems to be a performance boost in some cases, but it's not specified as being required by ECMA-262.

Why does Array(2) evaluate to [undefined × 2] instead of [undefined, undefined]?

See above, the console is just trying to be helpful. There are no undefined members at all, there is just an array with length 2. For the record, IE 10 shows:

[undefined, undefined]

which is also misleading for the above reasons. It should show [,,].

Why does [,] have a length: 1?

That is called an elision, which is part of an array initializer or array literal. It creates a "missing" member in the same way that:

var x = [];
x[0] = 0;
x[2] = 2;

does not have a member at index 1 and is equivalent to:

var x = [0,,2];

Noting again that old IE interpreted [,] as having length of 2. The member at index 1 is said to be "elided".


Post a Comment for "What Does [undefined × 2] Mean And Why Is It Different To [undefined,undefined]?"