What's the difference between Array(1) and new Array(1) in JavaScript?
With Array
, both are equivalent. The new
is injected when it's called as a function:
15.4.1 The
Array
Constructor Called as a FunctionWhen
Array
is called as a function rather than as a constructor, it creates and initialises a new Array object. Thus the function callArray(…)
is equivalent to the object creation expressionnew Array(…)
with the same arguments.
From ECMA-262, 3th Edition (with similar in 5th Edition). See also 22.1.1 The Array Constructor in ECMA-262 ECMAScript 2020 specification (11th Edition).
According to Javascript: The Definitive Guide (5th Edition), page 602, "When the Array()
constructor is called as a function, without the new
operator, it behaves exactly as it does when called with the new
operator."
The difference lies in the implementation of the Array function. Whether a call to Array without a new operator will return an instance of Array or not is implementation dependent. For example Mozilla's SpiderMonkey engine does this:
static JSBool
Array(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
jsuint length;
jsval *vector;
/* If called without new, replace obj with a new Array object. */
That is an actual comment from the actual source. Next lines of code are not reproduced here. I would suppose other engines do the same. Otherwise the behavior is undefined. A good read on this topic is John Resig's post here.
new
creates a new object (class instance) which is passed to constructor function as this
. But some functions detect if they were not called using new
and behave the same way as if they were. Array
is one of them, so there is no any difference.
If you want to create such constructor yourself you can do it like in following code:
function Smth(val) {
if (!(this instanceof Smth)) {
return new Smth(val);
}
this.val = val;
}