Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

The new operator

Reference for the JavaScript new operator: what it does step by step, constructors and classes, returning objects, new.target and common mistakes.

The new operator calls a function or class as a constructor and returns the new object. It creates an empty object whose prototype is the constructor's prototype property, runs the constructor with this bound to that object, and gives you the result.

Classes can only be called with new; plain constructor functions can be called without it, which is a classic source of bugs.

JavaScript
new Constructor
new Constructor(arg1, arg2)

Try it

JS Constructors and classes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Returning objects and calling without new

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new constructor
new constructor(...args)
new (getClass())(...args)
Part Description
constructor An expression that evaluates to a class or a function that can be constructed.
args Arguments passed to the constructor.

What happens:

  1. A new object is created with constructor.prototype as its prototype (or the prototype of new.target, when subclassing).
  2. The constructor runs with this set to the new object.
  3. If the constructor returns an object, that object is the result; otherwise the new object is.

Return value: the new object (or the object the constructor returned).

Exceptions: a TypeError if the value is not a constructor (arrow functions, methods, generators, async functions, and most plain values such as new 5). A TypeError also occurs for classes called without new. Errors thrown in the constructor propagate.

Usage notes

  • Classes require new. Calling Box() throws, which prevents the "forgot new" bug. Old-style constructors silently run with the wrong this (the global object in sloppy mode).
  • new X and new X() are equal. But new X().y and new X.y() differ: the first reads y from the instance, the second constructs X.y.
  • Built-in constructors: new Date(), new Map(), new Set(), new Error(), new Promise() and new Proxy() must use new. String(), Number() and Boolean() without new convert values to primitives, while with new they create wrapper objects. Avoid the wrapper form.
  • Subclasses: in a derived class, call super() before using this; new.target stays the class you called new on.
  • Factories as an alternative: a function that returns an object literal needs no new, and works with closures for private state.
  • Dynamic construction: new Foo(...args) accepts spread, and Reflect.construct(Foo, args) is the functional form.
  • Don't use new Object() or new Array() for literals: {} and [] are clearer.

Browser support

Supported in every browser and runtime. class syntax and new.target are available in all current browsers.