Tue Oct 31 2017

JavaScript Array Constructor Called as a Function

In a previous post I used new Array(4) to demonstrate generating a sequential list of numbers. It occurred to me that I have never actually typed new Array() before and have always used array literals instead.

I also wondered what happens if I drop the new operator as in Array(4)? Well nothing changes as it turns out that when calling the array constructor as a function a new array object is created for you.

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. Standard ECMA-262 5.1 Edition / June 2011

// (4) [0, 1, 2, 3]
// is the same as...
[ Array(4).keys()];
// (4) [0, 1, 2, 3]

I must have known this at some point but it has long been removed from the memory. Worth a quick refresh.