created by Brian LeRoux & Andrew Lunny. sparodically uncurated by David Trejo.

2013 07 18 array ruse

[,,,].join() // ==> ",,"



Turns out that the trailing comma is removed (trailing commas are allowed in javascript, but not JSON). Once removed, there are only three "elements" in the array, and both are undefined. When join is called, by default it uses a comma, yielding ",,". I think this is what happens.


JSON has nothing to do with this issue. Although a trailing comma is really allowed by Javascript and that's the case. So [1,2,3,] equals to [1,2,3]. So literally [,,,] is something like [undefined, undefined, undefined,]. You can add undefined to the end explicitly to get an array with 4 elements:

[,,,undefined].join() // ==> ',,,'


Each beginning or ending comma is Elision (except comma after AssignmentExpression). Each Elision are evaluated as one array field.

— [@tomi77]

Fork me on GitHub