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.
new Constructor new Constructor(arg1, arg2)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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:
- A new object is created with
constructor.prototypeas its prototype (or the prototype ofnew.target, when subclassing). - The constructor runs with
thisset to the new object. - 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. CallingBox()throws, which prevents the "forgotnew" bug. Old-style constructors silently run with the wrongthis(the global object in sloppy mode). new Xandnew X()are equal. Butnew X().yandnew X.y()differ: the first readsyfrom the instance, the second constructsX.y.- Built-in constructors:
new Date(),new Map(),new Set(),new Error(),new Promise()andnew Proxy()must usenew.String(),Number()andBoolean()withoutnewconvert values to primitives, while withnewthey create wrapper objects. Avoid the wrapper form. - Subclasses: in a derived class, call
super()before usingthis;new.targetstays the class you callednewon. - 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, andReflect.construct(Foo, args)is the functional form. - Don't use
new Object()ornew 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.
Related
- new.target
- instanceof
- this
- super
- Lessons: Classes, Prototypes, this