Using bracket notation, you can initialize an array with zero or more values:
var a= []; //length: 0, no items
var a= [1]; //length: 1, items: 1
var a= [1,2]; //length: 2, items: 1,2
Using new Array()
, you can initialize an array with zero or two or more values:
var a= new Array(0); //length: 0, no items
var a= new Array(1); //length: 1, items: undefined
var a= new Array(1,2); //length: 2, items: 1,2
Referring to the multiple-parameter syntax, in JavaScript: The Definitive Guide, Flanagan writes:
Using an array literal is almost always simpler than this usage of the Array() constructor.
He doesn't provide any examples in which the multiple-parameter syntax is simpler, and I can't think of any. But the words, "almost always" imply that there may be such instances.
Can you think of any?
Note that I understand the difference between the methods. My question specifically is, Why would you ever use the multiple parameter syntax with new Array()
? Flanagan implies that there may be a reason.
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
No. The array is not being created twice. It is being created once and then it is being populated.
Another way to create an array is to use the new keyword with the Array constructor. new Array(); If a number parameter is passed into the parenthesis, that will set the length for the new array with that number of empty slots. For example, this code will create an array with a length of 3 empty slots.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
The only time you should use new Array()
with any parameters is the single parameter case where you wish to create an (empty) array of the specified length.
There is no other case when new Array()
with any number of parameters (including zero) is preferred over an array literal.
Indeed the array literal should be used wherever possible, because whilst it's possible to overwrite the function Array()
so that it does something else (perhaps malicious) it's impossible to subvert the array literal syntax.
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