Array() vs new Array()

What is the difference (if there is any) between

x = Array()

and

x = new Array()

Which one should I use?

Answers:

Answer

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.

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.