Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Array syntax, multiple parameters

Tags:

javascript

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.

like image 501
Rick Hitchcock Avatar asked Mar 30 '15 13:03

Rick Hitchcock


People also ask

Can you have multiple types in an array?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

Can we initialize array two times?

No. The array is not being created twice. It is being created once and then it is being populated.

How do you create a new array?

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.

Can array store multiple elements?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.


1 Answers

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.

like image 169
Alnitak Avatar answered Sep 28 '22 08:09

Alnitak