Reputation: 87
I was initially looking up what happens on Array.prototype.toString()
. From the spec i realised this calls .join()
. But I don't understand the output on an array with undefined elements.
[,,,].toString()
returns ",,"
. But I expected ",,,"
. There appears to be 1 element missing in the serialization. What's happening here?
Upvotes: 1
Views: 672
Reputation: 7080
Because in JavaScript, the last ,
(the trailing comma) is ignored if it is followed by nothing.
console.log([1,].length);
// -> 1
console.log([1,,].length);
// -> 2
Therefore, when you are doing [,,,]
, the last ,
is ignored. Thus the length is only 3
.
console.log([,,,].length);
// -> 3
When you join an array with n
items, you get n-1
commas. Hence the result that you are getting.
Upvotes: 5
Reputation: 331
The last comma
in an array
is optional (for convenience) and therefore ignored in join()
Upvotes: 3