Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why trailing comma doesn't add undefined to javascript array?

Was writing a function that takes in an array of numbers and returns true and the index if there is a missing number or false if there are no missing numbers. I Just noticed something about arrays that confuses me.

An array like

[,1,2,3,4] 

will print

[undefined,1,2,3,4]

The array starts with a comma, Output makes sense to me

But why does

[1,2,3,4,] // Notice that the array ends with a comma

print

[1,2,3,4]  

I would have assumed the output would be [1,2,3,4,undefined].

Does anyone know why this is so?

like image 794
DevGalT Avatar asked Mar 23 '19 11:03

DevGalT


1 Answers

The trailing comma ("elision") is ignored:

If an element is elided at the end of an array, that element does not contribute to the length of the Array.

http://www.ecma-international.org/ecma-262/7.0/#sec-array-initializer

Note that only one comma is stipped on the right, so this [1,2,,] will be rendered as [1,2,undefined].

In Javascript arrays are just objects with a special length property, and an array initializer like

['a', 'b', 'c']

is a shortcut for

{
    "0": 'a', 
    "1": 'b', 
    "2": 'c',
    "length": 3
}

An elision makes the initializer skip the next index and increases the overall length, so this

['a', 'b', , 'c']

becomes this:

{
    "0": 'a', 
    "1": 'b', 
    "3": 'c'
    "length": 4
}

and two trailing elisions

['a', 'b', 'c', , ]

become

{
    "0": 'a', 
    "1": 'b', 
    "2": 'c', 
    "length": 4
}
like image 159
georg Avatar answered Sep 30 '22 05:09

georg