Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do elided array elements ever produce an own property?

In JavaScript when you define an array using the literal syntax, array elements may be omitted by using additional commas:

a = [1, 2, 3];   // 1, 2, 3
b = [1, , 2, 3]; // 1, undefined, 2, 3

I noticed that when accessing the values that the omitted values were not "own properties"

b.hasOwnProperty(1); //false

In contrast, if you define an array explicitly setting undefined, it will be set as an "own property":

c = [1, undefined, 2, 3];
c.hasOwnProperty(1); //true

Is the behavior for how omitted array elements are assigned defined in a spec? If so, which spec and where?

(optional bonus) Is it reliable cross-browser, such as evidenced by compatibility tables?

like image 427
zzzzBov Avatar asked May 09 '16 17:05

zzzzBov


1 Answers

Is the behavior for how omitted array elements are assigned defined in a spec?

Yes.

If so, which spec

The ECMAScript specification. At least in revisions 3, 5, 5.1 and 6.

and where?

In the semantics of array literal expressions, given by the Array Initializer section (ES5, ES6). It says

[…] the missing array element contributes to the length of the Array and increases the index of subsequent elements[, but they] are not defined.

In the evaluation of the expressions, they are simply skipped - they're counted but do not create a data property on the array instance, contrary to the assignment expressions that create the elements.

Is it reliable cross-browser?

Yes, even old Internet Explorers do it. The only quirks is that they count a trailing comma as an elision, which it should be not, and get the .length wrong.

like image 134
Bergi Avatar answered Oct 01 '22 06:10

Bergi