JavaScript: Literal Initialiser [] vs Constructor new Array() for Creating Arrays

The [] method is an array literal/array shorthand to initialise the array. The syntax is simple: a comma-separated list of values in square brackets []

The new Array() method is to create an instance by calling the array constructor.

The new Array() syntax has three different forms:

  1. If you call the constructor with TWO or more arguments, the arguments initialise the array with TWO or more elements.
  2. If you only supply ONE argument to the Array constructor, the argument initialises the length of the new array, but the new array’s elements are all undefined.
  3. If you call the constructor without arguments, the new array’s length is set to zero, the new array is empty array with no elements.

They are fundamentally similar. [] is preferable because it is pretty much shortcut for new Array(). However, there is a different when declaring the new array with specific length.

According to here new Array(5) will not return an array with a 5 init, instead, it will return a 5 element array with all the elements being undefined.

The only time you ever want to use new Array() instead of [], is when you want to have a large array with empty element. new Array(100) (the first argument passed into the constructor is the array length) is WAY shorter than [,,,,,,,,,,,, //omg too large to fit here]. But you can always do the same way like this:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA