What are the best practices to follow when declaring an array in Javascript?

Javascript

Javascript Problem Overview


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();?

Javascript Solutions


Solution 1 - Javascript

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().

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

  • 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

Solution 6 - Javascript

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("-");

Solution 7 - Javascript

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.

Solution 8 - Javascript

var array = [ 1, 2, 3, 4];

is sugar

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

is salt

Solution 9 - Javascript

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNaigelView Question on Stackoverflow
Solution 1 - JavascriptAlnitakView Answer on Stackoverflow
Solution 2 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 3 - JavascriptJL235View Answer on Stackoverflow
Solution 4 - JavascriptjAndyView Answer on Stackoverflow
Solution 5 - JavascriptYasir MahmoodView Answer on Stackoverflow
Solution 6 - JavascriptRANView Answer on Stackoverflow
Solution 7 - JavascriptErwin MollerView Answer on Stackoverflow
Solution 8 - JavascriptlinquizeView Answer on Stackoverflow
Solution 9 - JavascriptFlorentView Answer on Stackoverflow