There are at least three reasons people argue you should use the literal syntax ([...]
) rather than the array constructor:
The symbol
Array
can be shadowed (someone can give it a different meaning in a given scope), the literal cannot.The literal is shorter and, some would argue, clearer.
The
Array
constructor has a funny API:If you only give it one argument, then
- If that argument is a whole number, it uses that argument to set
length
. Sonew Array(10)
creates an empty array with alength
of 10.¹ - If the argument isn't a number, it uses that argument as the only element in the array. So
new Array("10")
creates an array with one element ("10"
) because"10"
isn't a number. - If the argument is a fractional number, it's an error. So
new Array(1.1)
fails with "invalid array length" or similar.
- If that argument is a whole number, it uses that argument to set
If you give it more than one argument, it creates an array with that many elements (even if the first argument is a whole number). So
new Array(10, 20)
creates an array with two elements (10
and20
).
This varying API is defined in this part of the spec.
¹ "...an empty array with a length
of 10" That may seem like a strange sentence — how can it be empty and have a length
of 10?! — but that's how JavaScript's "arrays" work. You could say they're sparse arrays. Or you could say they aren't really arrays at all. (This is true of the standard Array
; the new typed arrays, Int32Array
and such, are genuine arrays.)