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?
[] 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.
{} 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.
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.
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.
new Array(2)
proudces an array of size 2, containing two undefined
s. [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:
(new Array(X)).length == 1
for any X
as long as typeof(X) != "number"
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
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