Skip to content
jshacks.dev
Functions

Implement the new Operator From Scratch in JavaScript

Implement the new operator from scratch in JavaScript as a function that links the prototype, runs the constructor and handles object return values.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, npm, Node.js and TypeScript logos.

The new operator looks like magic: you write new Person("Ana") and get an object with the right properties and methods. The interview question asks you to write a function myNew(Constructor, ...args) that does the same job without using new. It is a good question because it checks that you understand what a constructor call really does: it creates an object, links its prototype, runs the function with that object as this, and then decides which object to return. This post builds myNew on Node.js 24 in those four steps, shows the surprising return-value rule, adds the checks for classes and arrow functions, and compares the result with the built-in operator.

What new does, step by step

The specification describes new F(...args) for an ordinary function as follows.

  1. Create a new empty object.

  2. Set its prototype to F.prototype.

  3. Call F with that object as this and the given arguments.

  4. If F returned an object, that object is the result. Otherwise the object from step 1 is the result.

Everything else is detail. Step 4 is the one candidates forget, and it is a standard follow-up.

The first version

JavaScript
function myNew(Constructor, ...args) {
  const instance = Object.create(Constructor.prototype);

  Constructor.apply(instance, args);

  return instance;
}

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function () {
  return `Hi, I am ${this.name}`;
};

const ana = myNew(Person, "Ana");

console.log(ana.name, ana.greet());
console.log(ana instanceof Person, Object.getPrototypeOf(ana) === Person.prototype);
Text
Ana Hi, I am Ana
true true

Object.create(Constructor.prototype) does steps 1 and 2 together: it makes an empty object whose prototype is the constructor's prototype property. apply does step 3. The greet method is found on the prototype chain, instanceof says true, and the prototype is the expected one. An older answer uses const obj = {}; obj.__proto__ = Constructor.prototype;, which works in practice and is discouraged: setting the prototype after creation is slower, and __proto__ is a legacy accessor.

The return value rule

A constructor can return something explicitly. If it returns an object, new gives you that object, and the freshly created one is thrown away. If it returns a primitive, the primitive is ignored.

JavaScript
function ReturnsObject() {
  this.kept = false;

  return { replaced: true };
}

function ReturnsPrimitive() {
  this.kept = true;

  return 42;
}

console.log(new ReturnsObject());
console.log(new ReturnsPrimitive());
console.log(myNew(ReturnsObject), myNew(ReturnsPrimitive));
Text
{ replaced: true }
ReturnsPrimitive { kept: true }
ReturnsObject { kept: false } ReturnsPrimitive { kept: true }

The built-in new ReturnsObject() yields the object the function returned, and new ReturnsPrimitive() ignores 42 and yields the new instance. Our first version always returns the instance, so myNew(ReturnsObject) gives ReturnsObject { kept: false }, which is wrong. The fix uses the return value of apply.

JavaScript
function myNew(Constructor, ...args) {
  const instance = Object.create(Constructor.prototype);
  const result = Constructor.apply(instance, args);

  const isObject = (typeof result === "object" && result !== null) || typeof result === "function";

  return isObject ? result : instance;
}

console.log(myNew(ReturnsObject), myNew(ReturnsPrimitive));
Text
{ replaced: true } ReturnsPrimitive { kept: true }

The test for "is an object" has to include functions. A constructor that returns a function gives that function back, and typeof on it is "function", not "object". And null must be excluded explicitly, because typeof null is "object", and a constructor returning null yields the instance. This one expression is the detail interviewers look for.

What if the prototype is not an object

If Constructor.prototype is not an object, for example it was set to a number, the real new falls back to Object.prototype for the instance. Object.create(5) would throw a TypeError.

JavaScript
function Weird() {
  this.ok = true;
}

Weird.prototype = 5;

const real = new Weird();

console.log(Object.getPrototypeOf(real) === Object.prototype, real.ok);

try {
  myNew(Weird);
} catch (error) {
  console.log(error.name);
}
Text
true true
TypeError

A faithful version picks Object.prototype when Constructor.prototype is not an object.

JavaScript
function myNew(Constructor, ...args) {
  if (typeof Constructor !== "function") {
    throw new TypeError(`${String(Constructor)} is not a constructor`);
  }

  const proto = Constructor.prototype;
  const prototype = (typeof proto === "object" && proto !== null) || typeof proto === "function" ? proto : Object.prototype;
  const instance = Object.create(prototype);
  const result = Constructor.apply(instance, args);

  return (typeof result === "object" && result !== null) || typeof result === "function" ? result : instance;
}

console.log(myNew(Weird).ok);
Text
true

This edge is rare in practice, and mentioning it shows that you have read the specification and not only the tutorials.

Arrow functions and methods are not constructors

Not every function can be called with new. Arrow functions, methods defined with shorthand syntax and async functions have no prototype and no [[Construct]] behavior, and new throws a TypeError for them.

JavaScript
const arrow = () => {};
const object = { method() {} };

for (const candidate of [arrow, object.method, async function () {}]) {
  try {
    new candidate();
  } catch (error) {
    console.log(error.name, candidate.prototype);
  }
}
Text
TypeError undefined
TypeError undefined
TypeError undefined

Our myNew, with its fallback to Object.prototype, would not throw for these. It would run the function with a new object as this and return that object. Whether a function can be constructed is not something JavaScript code can read directly. The common approximation is to check that Constructor.prototype exists, which excludes arrows and methods, and a way to test a function for being a constructor is to try Reflect.construct with a proxy or new inside a try. Say that you would not reimplement this check in production.

Classes

A class constructor cannot be called without new, so apply fails.

JavaScript
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

try {
  myNew(Point, 1, 2);
} catch (error) {
  console.log(error.name, "|", error.message);
}
Text
TypeError | Class constructor Point cannot be invoked without 'new'

Classes check at runtime that they were called as constructors. Our function calls Point as an ordinary function with apply, so it throws. Derived classes are even stricter: they do not have a this until super() runs. The language provides the correct tool for this case, Reflect.construct, which is the function form of new.

JavaScript
class Point3D extends Point {
  constructor(x, y, z) {
    super(x, y);
    this.z = z;
  }
}

const p = Reflect.construct(Point3D, [1, 2, 3]);

console.log(p, p instanceof Point);
Text
Point3D { x: 1, y: 2, z: 3 } true

Reflect.construct(Target, args, newTarget) performs the whole construct operation, including classes, super and new.target. The third parameter sets new.target, so you can construct an object with one class's constructor and another class's prototype. If an interviewer allows Reflect, that is the shortest correct answer, and the implementation above is what it does for plain functions.

JavaScript
function myNewReflect(Constructor, ...args) {
  return Reflect.construct(Constructor, args);
}

console.log(myNewReflect(Person, "Bo").greet());
Text
Hi, I am Bo

new.target

Inside a constructor called through new, new.target refers to the constructor. Called as a plain function, it is undefined. Our myNew calls the function with apply, so new.target is undefined inside it, and a constructor that checks for it, as many do to guard against a missing new, behaves differently.

JavaScript
function Guarded(value) {
  if (!new.target) {
    return new Guarded(value);
  }

  this.value = value;
}

console.log(new Guarded(1).value, Guarded(2).value, myNew(Guarded, 3).value);
Text
1 2 3

For myNew(Guarded, 3), new.target is undefined, so the guard calls new Guarded(3) and returns an object, which myNew then returns since it is an object. The result is correct, by luck: the constructor rescued itself. This is a good detail to mention if the conversation goes toward new.target, and the full topic is in new.target and functions called as constructors.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("myNew builds an instance with the right prototype", () => {
  function Box(v) {
    this.v = v;
  }

  Box.prototype.get = function () {
    return this.v;
  };

  const box = myNew(Box, 5);

  assert.equal(box.get(), 5);
  assert.ok(box instanceof Box);
});

test("myNew honors an object return value", () => {
  function Factory() {
    return { custom: true };
  }

  assert.deepEqual(myNew(Factory), { custom: true });
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

Where this knowledge helps

Understanding the four steps explains several behaviors that look odd. Methods defined on Constructor.prototype are shared by every instance, because each instance links to the same object, while properties assigned to this in the constructor are per instance. Forgetting new on an old style constructor in sloppy mode assigns properties to the global object, which is the reason so many constructors check new.target. And a factory function that returns an object literal is the same as a constructor that returns an object: the new operator is optional for it, since the returned object replaces whatever new made.

It also explains why instanceof can lie. The operator checks whether Constructor.prototype appears in the prototype chain of the object, so changing a constructor's prototype after creating instances makes instanceof return false for the old ones, which still point at the previous prototype object.

How to present it

Start with the four steps in plain language. Writing the first version takes a minute and gets you most of the credit. Then raise the return value rule yourself and fix it, because it is the detail that separates people who have memorized the pattern from those who understand it. If time remains, describe what the function cannot do: classes need Reflect.construct, and new.target is undefined inside the constructor because the call went through apply.

Avoid the __proto__ form in your answer, and say why: it is a legacy feature that reassigns the prototype after the object exists, which deoptimizes the object in engines, while Object.create sets the prototype at creation time.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.