'Why do we need the "new" keyword when creating an array?

Maybe I'm asking this incorrectly, but I'm primarily wondering what is the difference between creating an array with and without the "new" keyword? When is it appropriate to use?

var myPix = new Array("Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg"); 

I know that the the "new" keyword creates a new object. But, since I'm creating a variable that holds the array object, isn't the array still created without using "new"?

Lastly, couldn't I just as easily use this?

var myPix = ["Images/pic1.jpg", "Images/pic2.jpg", "Images/pic3.jpg"];


Solution 1:[1]

You can do this either way.

In JavaScript, everything is an object including arrays and a typical way to instantiate is to use the keyword new. But, for a few cases including array, this can be avoided by declaring an array like this:

var arr = [3,45,43,4]; 

however, the second way (using []) of creating an array is preferred because:

  1. it is simpler
  2. it is faster

See discussion here - Why is arr = [] faster than arr = new Array?

Solution 2:[2]

We don't need the new keyword for Array() because is has "exotic" behavior mandated by the ECMAScript standard:

The Array constructor:

...

  • creates and initializes a new Array when called as a constructor.
  • also creates and initializes a new Array when called as a function rather than as a constructor. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

Solution 3:[3]

using new Array("a", "b", "c") is equivalent to ["a", "b", "c"]. The latter is called Javascript Object Notation and is more script-like ala languages such as python. The returned object is still an Array in either case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 qwr
Solution 3 Andrew Luo