What is the difference (if there is any) between
x = Array()
and
x = new Array()
Which one should I use?
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.
{} 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.
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.
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.
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 callArray(…)
is equivalent to the object creation expressionnew Array(…)
with the same arguments.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With