Array() vs new Array()

JavascriptArrays

Javascript Problem Overview


What is the difference (if there is any) between

x = Array()

and

x = new Array()

Which one should I use?

Javascript Solutions


Solution 1 - Javascript

The spec says:

> When Array is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.

Solution 2 - Javascript

You should use the literal []. Reasons are outlined here. Using the Array() constructor can be ambiguous, since it accepts either a length or a list of elements:

new Array(5)   // []
new Array('5') // ['5']

[5]   // [5]
['5'] // ['5']

The reason you can use Array without the new operator is that internally it does a common trick with constructors:

function Thing(){
    if (!(this instanceof Thing)){
        return new Thing()
    }
    // ... define object
}

That is, if you call Thing() it will call new Thing() for you.

Solution 3 - Javascript

I believe that both are equivalent. However, in JavaScript at least, you should always use the literal syntax:

x = []

But based on some tests in the browsers I have, Array(1, 2, 3) gives the same result as new Array(1, 2, 3), and same with Array(15) and new Array(15). Or just plain new Array().

Solution 4 - Javascript

Some facts that worth to mention:

Array === Array.prototype.constructor //true

and

new Array() does the same as new Array and [] as well

However, the result of calling a constructor is not necessarily equivalent to creating a new instance of an object. Example:

Foo = function(){}

x = Foo()   // undefined
y = new Foo // {}

So x and y can be different.

But if the Object itself is an Array you will get the same by definition, as mentioned earlier.

x = Array()   // []
y = new Array // []

Even if you pass one integer (telling the length)

x = Array(3)     // [empty × 3]
y = new Array(3) // [empty × 3]

or one non integer (telling the content)

x = Array(true)     // [true]
y = new Array(true) // [true]

or more parameters (telling the content)

x = Array(1,2,3)     // [1,2,3]
y = new Array(1,2,3) // [1,2,3]

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
QuestionscravyView Question on Stackoverflow
Solution 1 - JavascriptSLaksView Answer on Stackoverflow
Solution 2 - JavascriptRicardo TomasiView Answer on Stackoverflow
Solution 3 - JavascriptRy-View Answer on Stackoverflow
Solution 4 - JavascriptAlex SzücsView Answer on Stackoverflow