I'm trying to get myself around the insights of JavaScript, currently learning it.
At arrays, I've been reading that the followng is an anti-pattern :
var a = new Array("a", "b", "c");
and the the following, is not :
var a = ["a", "b", "c"];
I'm often having hard times with understanding javascript, because I'm tempted to make analogy with c# altough, I shouldn't! Could you please explain me why is this?
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
length. So new Array(10) creates an empty array with a length of 10.¹new Array("10") creates an array with one element ("10") because "10" isn't a number.new Array(1.1) fails with "invalid array length" or similar.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 and 20).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With