Why does `Array ()` and `Array ()` behave the same in Javascript?

Here are 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've seen several comments about " never use Array with new ". But I can't figure out how I found that Array

and that both new Array

seem to behave the same in Javascript. Why do they behave the same? And why should one use be preferred over another?

I know that only literal syntax should be used []

instead Array

, I'm just wondering what Array

is.

Is this a constructor function? If this is a constructor function, why can we use it without new

?

+3


source to share


1 answer


When Array

called as a function rather than a constructor, creates and initializes a new Array object. Thus, calling a function is Array(…)

equivalent to creating an object new Array(…)

with the same arguments.



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

+8


source







All Articles