What is the difference between Array () and [] in Javascript and why should I use one over the other?

Possible duplicate:
What is the difference between "Array ()" and "[]" when declaring a JavaScript array?

In JavaScript, you can create a new array, for example:

var arr = new Array(); 

or how:

 var arr2 = []; 

What is the difference and why are you doing one on top of the other?

+6
javascript arrays literals
source share
3 answers

new Array(2) takes pride in an array of size 2 containing two undefined s. [2] creates an array of size 1 containing number 2. new Array IMO does not conform to the spirit of JavaScript, although it can make the construction of the array much more accessible. This may or may not make any difference (I use literals almost exclusively in JavaScript for all applicable types, and I created or supported large snippets of JavaScript [30-50 KLOC] successfully).

edit I think the reasons chained by javascript programmers are avoiding the new Array syntax:

  • it does not behave uniformly in the numbers and types of arguments ( (new Array(X)).length == 1 for any X , while typeof(X) != "number"
  • This is more detailed and the only thing you get is unevenness.
+4
source share

Another (minor) reason to use [] in the new Array() preference is that Array can potentially be overridden (although I never saw it) and [] guaranteed to work.

 Array = "something"; var a = new Array(); // Fails var b = []; // Works 
+2
source share

I believe that they are identical. I never use a new array ();

0
source share

All Articles