-1

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
  • 44,755
  • 7
  • 76
  • 106
Gaurav
  • 123
  • 7
  • 7
    Possible duplicate of [Array() vs new Array()](https://stackoverflow.com/questions/8205691/array-vs-new-array) and [What the different between `new Array(n)` and `Array(n)`](https://stackoverflow.com/questions/35263876) – adiga May 17 '19 at 14:26

1 Answers1

-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.
Community
  • 1
  • 1
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98