JavaScript `new` Operator Semantics

The JavaScript `new` operator creates an object, connects it to the constructor's prototype, calls the constructor with that object as `this`, and normally returns the object. If the constructor explicitly returns an object, that returned object replaces the newly created one; primitive returns are ignored.

When `new Constructor()` is evaluated, JavaScript first creates a new object whose internal prototype is based on `Constructor.prototype`. This establishes the object's prototype-chain relationship before the constructor body runs.

The constructor is then called with the new object bound as `this`. Properties assigned with `this`, such as `this.name = name`, therefore become own properties of the newly created object.

After the constructor finishes, the result depends on its return value. If it returns an object or function, that value becomes the result of the `new` expression. If it returns a primitive value, that value is ignored and the originally created object is returned.

Classes use constructor semantics with `new`: calling a class constructor without `new` throws a `TypeError`. Ordinary functions can also be used with `new` when their call semantics permit construction.

Key points

Interview questions

What happens when you use `new` with a constructor function?

JavaScript creates a new object and establishes its prototype relationship using the constructor's `prototype` value. It then invokes the constructor with that object as `this`. If the constructor returns an object or function, that returned value becomes the result. Otherwise, the newly created object is returned.

Why does `new Foo()` have access to methods on `Foo.prototype`?

The object produced by `new Foo()` is created with a prototype related to `Foo.prototype`. Property lookup can therefore continue from the new object's own properties to that prototype. Methods placed on `Foo.prototype` can be shared by instances rather than copied onto every object.

What if a constructor explicitly returns a value?

An object or function returned by the constructor becomes the result of the `new` expression. A primitive return value does not replace the object created by `new`. This behavior can produce surprising results if a constructor accidentally returns an object.

How does `new` differ from `Object.create()`?

Both can produce an object with a chosen prototype relationship, but they serve different purposes. `Object.create(proto)` creates an object using `proto` as its prototype and does not execute a constructor. `new Constructor()` also performs constructor invocation and supplies the created object as `this`.

Can every JavaScript function be used with `new`?

No. A function must have construction semantics to be usable with `new`. Arrow functions are not constructable, so `new (() => {})` throws a `TypeError`. Classes are constructable but are intentionally not callable as ordinary functions.