Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

In JavaScript you can create a new array like:

var arr = new Array();

or like:

var arr2 = [];

What is the difference and why would you do one over the other?

like image 775
cmcculloh Avatar asked Feb 04 '10 22:02

cmcculloh


People also ask

Whats the difference between {} and [] in array?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

What is the difference between {} and []?

The difference between “{}” and “[]” is that {} is an empty array while [] is a JavaScript array, but there are more! In JavaScript, almost “everything” is an object. All JavaScript values, except primitives, are objects.


2 Answers

new Array(2) proudces an array of size 2, containing two undefineds. [2] produces an array of size 1, containing number 2. new Array IMO doesn't fit with the spirit of JavaScript, even though it may make array construction much more findable. That may or may not be of any importance (I use literals almost exclusively in JavaScript for all applicable types, and I've authored/maintained large pieces of JavaScript [30-50 KLOC] successfully).

edit I guess the reasons seasoned javascript programmers avoid new Array syntax are:

  • it doesn't behave uniformly across argument numbers and types ((new Array(X)).length == 1 for any X as long as typeof(X) != "number"
  • it's more verbose and the only thing you gain is the irregularity
like image 140
just somebody Avatar answered Oct 31 '22 13:10

just somebody


Another (minor) reason to use [] in preference to new Array() is that Array could potentially be overridden (though I've never seen it happen) and [] is guaranteed to work.

Array = "something";
var a = new Array(); // Fails
var b = []; // Works
like image 29
Tim Down Avatar answered Oct 31 '22 12:10

Tim Down