new Operator
JavaScript · Reference cheat sheet
new Operator
JavaScript · Reference cheat sheet
📋 Overview
new constructs an instance from a constructor function or class. It creates an object, sets its prototype, binds this, and returns the object (unless the constructor returns another object).
🔧 Core concepts
- Steps: create
\{\}→ set[[Prototype]]→ call constructor withthis→ return object (or explicit object return). - Classes:
new Person()required; calling withoutnewthrows. new.target: meta-property detecting construct calls.new.target/ subclassing: works withextendsandsuper.- Built-ins:
new Map(),new Date(),new Error()— some built-ins differ if called as functions.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);💡 Examples
// Classic constructor
function User(name) {
if (new.target === undefined) {
return new User(name); // allow factory-style call
}
this.name = name;
}
User.prototype.hello = function () {
return `Hi, ${this.name}`;
};
const u = new User("Ada");
u instanceof User; // true
Object.getPrototypeOf(u) === User.prototype; // true
// Class fields & private
class Counter {
#n = 0;
get value() {
return this.#n;
}
inc() {
this.#n += 1;
}
}
const c = new Counter();
// Return override
function Weird() {
this.a = 1;
return { b: 2 }; // instance discarded
}
new Weird(); // { b: 2 }
// Reflect.construct
const d = Reflect.construct(Date, [2026, 0, 1]);// Array exotic
const a = new Array(3); // length 3 sparse
const b = Array.of(3); // [3]⚠️ Pitfalls
- Forgetting
newon old constructors sets properties on the global/undefined(strict) — preferclass. - Returning a primitive from a constructor is ignored; returning an object replaces
this. arrow functionscannot be constructors — nonew.Symbol/BigIntare not constructible withnew.instanceofcan be spoofed; use brands ornew.targetchecks for security-sensitive code.
🔗 Related
- oop.md — classes & inheritance
- objects.md — prototypes
- properties.md — defining instance props
- error.md —
new Error - map.md —
new Map - date.md —
new Date