177

When I need to declare a new array I use this notation

var arr = new Array();

But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."

I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []? Or is it bad practice?

Is there a good reason to use var arr = []; instead of var arr = new Array();?

5
  • 5
    Both are fine. You just save some bytes in transmission.
    – Sirko
    Jul 16, 2012 at 8:22
  • 14
    There are indeed differences. See this post: stackoverflow.com/q/2280285/921204
    – techfoobar
    Jul 16, 2012 at 8:25
  • Note: there are differences if Array has been overwritten only.
    – crdx
    Jul 18, 2012 at 12:19
  • @apkd on some browsers there's a significant performance difference
    – Alnitak
    Jul 18, 2012 at 17:36
  • Fair enough. I didn't see that on the linked question.
    – crdx
    Jul 19, 2012 at 7:18

9 Answers 9

262

Mostly, people use var a = [] because Douglas Crockford says so.

His reasons include the non-intuitive and inconsistent behaviour of new Array():

var a = new Array(5);     // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it

Note that there's no way with new Array() to create an array with just one pre-specified number element in it!

Using [] is actually more efficient, and safer too! It's possible to overwrite the Array constructor and make it do odd things, but you can't overwrite the behaviour of [].

Personally, I always use the [] syntax, and similarly always use {} syntax in place of new Object().

5
  • 5
    "you can't overwrite the behaviour of []." Are you sure about this? I thought that you could overwrite the Array constructor to affect [], and the Object constructor to affect {}, at least on some implementations.
    – Random832
    Jul 16, 2012 at 16:54
  • 12
    @Random832 maybe in older browsers, but not in ES5 compatible implementations, where the spec says that [] calls an internal constructor, not whatever value Array.constructor happens to have at the time.
    – Alnitak
    Jul 16, 2012 at 19:09
  • 5
    Bonus: Array literals are much faster than creating new arrays using the Array constructor: jsperf.com/new-array Jul 17, 2012 at 19:09
  • @MathiasBynens only sometimes.
    – OrangeDog
    Jul 18, 2012 at 13:13
  • Ew @ the [] working differently because of the internal constructor thing. The inconsistency will cause more confusion than it saves. Edit: Ah, security concern. I get it. May 23, 2013 at 0:22
48

One significant difference is that [] will always instantiate a new Array, whereas new Array could be hijacked to create a different object.

(function () {
    "use strict";
    var foo,
        bar;
    //don't do this, it's a bad idea
    function Array() {
        alert('foo');
    }
    foo = new Array();
    bar = [];
}());​

In my example code, I've kept the Array function hidden from the rest of the document scope, however it's more likely that if you ever run into this sort of issue that the code won't have been left in a nice closure, and will likely be difficult to locate.

Disclaimer: It's not a good idea to hijack the Array constructor.

2
  • 7
    IIRC, in older browsers overriding the Array constructor would also cause literals to be interpreted incorrectly. There was a GMail CSRF vulnerability a while ago the involved overriding the array constructor and new browsers ignore overloading for literals for this precise reason.
    – hugomg
    Jul 17, 2012 at 13:51
  • Counter-disclaimer: it has however been exceedingly helpful and useful to enhance the Array constructor over the years. May 23, 2013 at 0:23
26

for maintainability, use []

The array literal is more predictable, as most developers use it. Most array usage out there will be using the literal, and there is value in having your code match up with what other developers use.

for empty arrays, use []

var ns = [];
var names = [ 'john', 'brian' ];

As shown here, using the literal for empty and a couple of known elements is fatster than the Array constructor.

for an array of known size, use new Array(size)

If the size is known, then using the Array constructor significantly improves performance. However it also means you have to deal with an array which already has 'undefined' filling all it's values.

As shown here

// fill an array with 100 numbers
var ns = new Array( 100 );
for ( var i = 0; i < 100; i++ ) {
    ns[i] = i;
}

This also works for very small arrays too.

12

No, there is actually no reason to use one notation over the other one for empty Arrays.

However, most browsers show a slightly better performance using x = []; than calling the Constructor.

If you need to create an Array with a specific size, you kind of need to use x = new Array(10); for instance, which would create an Array with 10 undefined slots.

4
  • @Alnitak: which you already mentioned, is not very intuitive and concise.
    – jAndy
    Jul 16, 2012 at 8:28
  • 7
    I put together a jsperf to compare performance: jsperf.com/array-constructor-versus-literal. At least for me on Chrome 20 on Ubuntu, the literal is twice as fast as the constructor.
    – Steven
    Jul 16, 2012 at 13:22
  • 1
    @jAndy, I can think of one difference for empty arrays.
    – zzzzBov
    Jul 16, 2012 at 14:11
  • jAndy, why would you want an array with "10 empty slots" in JavaScript? In reality, you can do the exact same thing with: var arr = []; arr[9] = "omega"; 1. Arrays in JS are totally dynamic, you can reference any index you would like, and it will just be "undefined". This is just as true as if you were to say: var arr = new Array(10); arr[23]; 2. the array's length is going to be set to the highest value that has anything in it, regardless of how many undefined slots are in between. Or you can set it, yourself. [] might not cure cancer, but it marginally-better.
    – Norguard
    Jul 17, 2012 at 6:34
7
  • var arr=[] uses the array/object literal
  • var arr = new Array() use the array/object constructor

The speediest way to define an array or object is literal way, because you don't need to call the constructor

var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];

alert(arr1[0]); // 1
alert(arr2[0]); // 1

var arr3 = new Array(200);
var arr4 = [200];

alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
1
  • 2
    For reference, behind the scenes, var arr = []; logically uses a constructor too. It's just always the built-in array constructor, rather than whatever function is currently going by the name Array.
    – cHao
    Jul 16, 2012 at 15:13
6

Both are correct only. But most of the people use var a = []

Three Ways to Declare an Array in JavaScript.

method 1: We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available).

// Declare an array (using the array constructor)
var arlene1 = new Array();
var arlene2 = new Array("First element", "Second", "Last");

method 2: we use an alternate method to declaring arrays.

// Declare an array (using literal notation)
var arlene1 = [];
var arlene2 = ["First element", "Second", "Last"];

method 3: JavaScript also lets you create arrays indirectly, by calling specific methods.

// Create an array from a method's return value
var carter = "I-learn-JavaScript";
var arlene3 = carter.split("-");
4

There is a limit the constructor can take as arguments.

On most systems I encoutered the limit is 2^16 (2 bytes):

var myFreshArr = new Array(0,1,2,3 ..... 65536);

That will cause an error (too many arguments....)

When using the literal [] you don't have such problems.

In case you don't care about such big arrays, I think you can use whatever you prefer.

2
  • 2
    Can you cite an example of where a person might reasonably want to create an array pre-populated with 70,000 values? Though, it does really explain some of the awful websites I've seen that never seem to finish loading...
    – John O
    Jul 16, 2012 at 19:45
  • 2
    John O, I've seen some SCARY JSON implementations in my time, involving arrays of 2D/3D arrays, featuring IATA(airport) codes, airline-companies, tour-operators, resorts, et cetera... ...all stuffed into one array. It's... ...1MB+ JSON downloads make me want to cry.
    – Norguard
    Jul 17, 2012 at 6:38
4
var array = [ 1, 2, 3, 4];

is sugar

var array = new Array(1, 2, 3, 4);

is salt

1
  • 5
    and where to use it, for coffee or for pasta ?
    – Aristos
    Jul 16, 2012 at 17:12
3

It's because new Array() is ambiguous. These are the correct constructors:

// Using brackets
[element0, element1, ..., elementN]

// Using new AND a list of elements
new Array(element0, element1, ..., elementN)

// Using new AND an integer specifying the array length
new Array(arrayLength)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.