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


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 [].”


Solution 1:




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 [].


Solution 2:


(function () {
    "use strict";
    var foo,
    //don't do this, it's a bad idea
    function Array() {
    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.

Related:  How to get a content script to load AFTER a page's Javascript has executed?

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

Solution 3:

for maintainability, use []


for empty arrays, use []

var ns = [];



all it’s values.

As shown here

// fill an array with 100 numbers
var ns = new Array( 100 );
    ns[i] = i;

This also works for very small arrays too.

Related:  Resolving spring:messages in javascript for i18n internationalization

Solution 4:




Solution 5:

  • var arr=[] uses the array/object literal

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


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

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

alert(arr4[0]); // 200

Solution 6:


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

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

// Declare an array (using literal notation)
var arlene1 = [];


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