views:

1735

answers:

6

Whats the real difference between declaring an array like this:

var myArray = new Array();

and

var myArray = [];
+19  A: 

There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

x = new Array(5);
alert(x.length); // 5

To illustrate the different ways to create an array:

var a = [],            // these are the same
    b = new Array(),   // a === b

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c === d

    // these are different:
    e = new Array(3),   // e.length == 3, e[0] == undefined
    f = [3]             // f.length == 1, f[0] == 3
;
nickf
This is slightly wrong. There is one very important difference between new Array() and [] I'll elaborate in my answer.
coderjoe
But as noted in your answer, it's only different if you are completely insane and overwrite the Array function..?
nickf
Well the importance is that using the new operator causes the interpreter to take all sorts of extra steps to go to the global scope, look for the constructor, call the constructor and assign the result... which in the majority case is going to be a a runtime array. You can avoid the overhead of looking for the global constructor by just using []. It may seem small, but when you're shooting for near real-time performance in your app, it can make a difference.
coderjoe
+3  A: 

Here is a piece of JavaScript code that will verify that both declarations lead to the same type:

var test1 = [];
test1.push("value");

var test2 = new Array();
test2.push("value");

alert(typeof(test1) == typeof(test2));
Fredrik Mörk
Information from typeof can be misleading. In the case of arrays, type of reports that they're objects, which is sort of true since Arrays inherit from objects, but that means the above test codes doesn't really verify anything.
Alan Storm
@Alan; I ran tests with typeof against strings and ints, but I guess it won't distinguish arrays from complex types. Thanks for pointing it out.
Fredrik Mörk
+3  A: 

The first one is the default object constructor call. You can use it's parameters if you want.

var array = new Array(5); //initialize with default length 5

The second one gives you the ability to create not empty array:

var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
Bogdan Gusiev
You can do the same thing with verbose constructor: var array = new Array(1, 2, 3);
nickf
So then I guess you can do `var array = [5]` using the square brackets but not using the constructor as `var array = Array(5)` makes an empty array of 5 elements.
cdmckay
cdmckay - that's incorrect. var a=[5] would be an array with a single item - the number five.
BarelyFitz
@BarelyFitz: That's what I said. In Bogdans' answer, he says that the constructor call can't be used to initalize an array, but he was wrong. My comment was merely to clarify that you can't use the constructor call to initialize an array of a single element.
cdmckay
@cdmckay: sorry, I misunderstood your comment. To clarify: new Array(arg) - if arg is numeric this creates an empty array with length=arg; new Array(arg1, arg2) - creates a new array and initializes the array elements. So if you want to create an array with one numeric element like [5], you cannot do it using new Array(5). But really you should never use new Array() so this is a moot point.
BarelyFitz
Also new Array('foo') would create an array with a single element, however, this can only be used when the arg is non-numeric.
BarelyFitz
+3  A: 

For more information, the following page describes why you never need to use new Array():

http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

BarelyFitz
Crockford, also, says to use [] rather than new Array(). Unfortunately, he doesn't say why in the linked article. I assume it's just a matter of space and speed. http://javascript.crockford.com/code.html
Nosredna
Crockford's not a fan of the using the "new" keyword to create a new instance of an object in Javascript. In lectures he's stated it's his belief that it creates ambiguity and doesn't fit in well with Javascript's prototype style inheritance. He's specifically referring to user created object constructors, but given that belief, it's easy to see why he'd recommend you not use it with the built-ins as well when there's an alternative syntax.
Alan Storm
@Alan Storm: at least for Number, String, and Boolean he says "these forms produce unnecessary object wrappers", but I guess that wouldn't apply to Array.
BarelyFitz
+18  A: 

The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {
 this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);
alert(b.is);
b.push('Woa');
a.push('Woa');

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as 'push', where the other does not.

While you may expect this to happen, it just illustrates the fact that '[]' is not the same as 'new Array()'.

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

Cheers!

coderjoe
Well, good to know I suppose. What sort of person would overwrite the array class, I do not know...
nickf
You're absolutely right. Only a madman would overwrite the array class. Now take a moment and consider all the extra work using new Array() makes the interpreter do to support these madmen. I just avoid it all together with [].
coderjoe
Good example of the kind of global pollution that is possible with JavaScript.
David Caunt
+3  A: 

Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.

galambalazs