Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
Hanfei Sun Avatar asked Sep 24 '26 09:09

Hanfei Sun


1 Answers

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

like image 97
zerkms Avatar answered Sep 27 '26 00:09

zerkms