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.
newOperator(Constructor: Function, ...args: any[]): object
// mirrors `new Constructor(...args)`
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
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.newOperator returns that instead of the instance.null, or undefined return is discarded and the caller gets the instance. Watch null: typeof null is 'object', so it needs an explicit guard.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.