Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array() vs new Array()

What is the difference (if there is any) between

x = Array()

and

x = new Array()

Which one should I use?

like image 947
scravy Avatar asked Nov 20 '11 23:11

scravy


People also ask

What is difference between array and new array?

new Array() There are no differences between calling Array() as a function or as a constructor. According to the spec, using Array(…) as a function is equivalent to using the expression new Array(…) to create an Array object instance with the same arguments.

What is difference between {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

What does new array mean?

The var weekday = new Array( 7 ); is declaring an array with 7 items in it, as shown by the following lines. The array stores values at each index( number ) and you access the values via variable[#] You do not need it in javascript but many other languages such as Java require an explicit value.

Why do we use new array?

If you run Array() without the new , you're skipping to that second step without creating any object to initialize. With its built-in type functions like Array , Javascript will turn around and create the object for you even when called without new ; they "do the right thing" because they're written that way.


3 Answers

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.

like image 67
SLaks Avatar answered Oct 17 '22 07:10

SLaks


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.

like image 39
Ricardo Tomasi Avatar answered Oct 17 '22 06:10

Ricardo Tomasi


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

like image 9
Ry- Avatar answered Oct 17 '22 05:10

Ry-