Hanfei Sun
Hanfei Sun

Reputation: 47091

Why `new Array()` and `Array()` behaves the same in Javascript?

Here is the examples

Array(1,2,3)
> [1,2,3]
new Array(1,2,3)
> [1,2,3]
Array(3)
> [undefined, undefined, undefined]
new Array(3)
> [undefined, undefined, undefined]

I saw some comments about "never use Array with new". But I can't understand as I found Array and new Array seems to behave the same in Javascript.. Why do they behave the same? And why should one usage be preferred over the other?

I know [] literal syntax should usually be used instead of Array, I was just wondering what Array is..

Is it a constructor function? If it is a constructor function, why could it be used without new?

Upvotes: 3

Views: 108

Answers (1)

zerkms
zerkms

Reputation: 255135

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.

http://es5.github.io/#x15.4.1

Upvotes: 8

Related Questions