6

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.

Rick Hitchcock
  • 33,093
  • 3
  • 40
  • 70

3 Answers3

4

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.

Alnitak
  • 313,276
  • 69
  • 379
  • 466
2

By simpler he is probably referring to the fact that it is shorter, easier to write, more explicit and you may have issues with things like:

var test = new Array(1) //Empty array 
var test2 = [1] //not empty
Bouthaina
  • 27
  • 4
  • questions is not how it is different, Using an array literal is almost always simpler than this usage of the Array() constructor, **with multiple parameters**? – Naeem Shaikh Mar 30 '15 at 13:41
2

I don't think he meant that there are cases where using the multiple-parameter syntax is simpler, but there are cases (only one I can think of) where using the Array constructor is simpler: Creating an array of size N.

javinor
  • 664
  • 5
  • 8