Why are these two statements the same in JavaScript?
var a = new Array(5);
var a = Array(5);
Or, if they are not the same, what is different about them? Basically if I assign a to a different variable and mutate it, the values in the array change for each initialization in a similar way.
ggorlen
59.5k9 gold badges119 silver badges174 bronze badges
1 Answer 1
Why are these two statements the same in JavaScript?
var a = new Array(5); var a = Array(5);
That's just the way Array was designed. Not all constructors have this behavior, but the Array constructor's specification is such that it can be called either with new or without.
From the ECMAScript spec:
22.1.1The Array Constructor
[...]
- also creates and initializes a new Array object when called as a function rather than as a constructor. Thus the function call Array(...) is equivalent to the object creation expression new Array(...) with the same arguments.
answered May 17, 2019 at 14:26
Nicholas Tower
87.2k10 gold badges115 silver badges127 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
new Array(n)andArray(n)