All questions

The new Operator

Premium

The new Operator

The new operator builds an object from a constructor function in four steps: it creates a fresh object, links that object to the constructor's prototype, runs the constructor with this bound to the object, then returns the object. Implement newOperator(Constructor, ...args) so it reproduces exactly what new Constructor(...args) does — the same instance, the same prototype chain, the same instanceof result — without using the new keyword yourself. This is a classic JavaScript-internals interview question; see MDN's new reference for the language's own description.

Signature

newOperator(Constructor: Function, ...args: any[]): object
//   mirrors `new Constructor(...args)`

Examples

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.greet = function () {
  return 'Hi, I am ' + this.name;
};

const p = newOperator(Person, 'Ada', 36);
p.name;              // 'Ada'
p.greet();           // 'Hi, I am Ada'  (inherited from the prototype)
p instanceof Person; // true
// If the constructor returns an OBJECT, that object wins:
function Weird() {
  this.ignored = true;
  return { custom: 'value' };
}
newOperator(Weird); // { custom: 'value' } — not the instance

// If it returns a PRIMITIVE (or null / undefined), the return is ignored:
function Ok() {
  this.value = 1;
  return 42; // discarded
}
newOperator(Ok); // { value: 1 } — the instance

Notes

  • The four steps — create a plain object, set its prototype to Constructor.prototype, call the constructor with this bound to that object, then return an object result or the object you made.
  • instanceof must work — the result has to satisfy newOperator(Foo) instanceof Foo, and it must inherit methods defined on Foo.prototype. Use Object.create or Object.setPrototypeOf to link the prototype.
  • Object return overrides — if the constructor returns an object, an array, or a function, newOperator returns that instead of the instance.
  • Primitive return is ignored — a number, string, boolean, null, or undefined return is discarded and the caller gets the instance. Watch null: typeof null is 'object', so it needs an explicit guard.
  • Do not use new — reproduce the behavior with Object.create (or Object.setPrototypeOf) plus Function.prototype.apply. Calling the real new defeats the exercise.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium