1

I was recently bitten by a bug where there accidentally was one too many commas in a JavaScript array which brings us to todays question: Why is

[1, 2,  , 4, 5]

a valid JavaScript array and not a syntax error? Is it clearly defined in the ECMAScript standard that emply elements should be allowed? It seems like such an easy typo to make.

For further information it can be noted that [1, 2, , 4, 5][2]; is undefined.

2 Answers 2

4

These kind of arrays are called sparse arrays.

http://2ality.com/2012/06/dense-arrays.html

Sign up to request clarification or add additional context in comments.

Comments

2

Is it clearly defined in the ECMAScript standard that emply elements should be allowed?

Yes, it is. See https://tc39.github.io/ecma262/#sec-array-initializer

Array elements may be elided at the beginning, middle or end of the element list [of an ArrayLiteral]. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

In the grammar, look for the nonterminal Elision.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.