2

Consider the following snippet :-

function Custom(){}

// prints {}
console.log(Object()); 
// prints []
console.log(Array());
// prints undefined
console.log(Custom())
// prints {}
console.log(new Custom());

I know that the Custom function constructor needs a new keyword prefixed to bind this. Why isn't that necessary for Array and Object constructors ?

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • Because `Custom()` is a function and it doesn't return anything. Unless you [call it with `new`](https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) in which case it's the `new` operator that will instantiate and return an object. You can change `Custom()` to return something, then you wouldn't (necessarily) need `new` – VLAZ Jun 16 '21 at 05:27
  • perhaps it's a historical convention - you can make your own `Custom` not require `new` if you really want – Jaromanda X Jun 16 '21 at 05:27

2 Answers2

5

The array constructor says:

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.

The object constructor says:

  1. If NewTarget is neither undefined nor the active function, then a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
  2. If value is undefined or null, return ! OrdinaryObjectCreate(%Object.prototype%).
  3. Return ! ToObject(value).

So it's explicitly noted that new isn't required for either of those.

(though, you should probably never be using either Object or Array as constructors, whether with or without new - better to use object and array literals)

It'll be trivial to implement this sort of thing yourself in Custom, if you want - check if the function was called with new, and if not, explicitly return something:

function Custom(){
  if (!new.target) {
    return new Custom();
  }
}
console.log(Custom())
console.log(new Custom());
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Custom, Object, and Array all are functions. When you call them, i.e. Object(), the value printed is the return value of the function. Object and Array returns a new empty object and array respectively. While the Custom function returns nothing and thus undefined is printed.

When you call a function with new is creates an object by calling the function as a constructor. As one of the comments mentioned This gives more details about the new keyword.

Ahzaz
  • 88
  • 6