JavaScript · The language round
What does the new operator do?
Short answer
new creates an object, links it to the constructor's prototype, runs the constructor with this bound to the new object, and returns that object unless the constructor explicitly returns another object.
The new keyword is a four-step operation. Knowing the steps explains why constructors behave the way they do and why returning a value from one can be surprising.
- Create a new empty object
- Set its prototype to
Constructor.prototype - Call the constructor with
thisset to the new object - Return the object, unless the constructor returns a different object
function User(name) {
this.name = name;
}
User.prototype.greet = function () {
return "Hi, " + this.name;
};
const user = new User("Asha");
console.log(user.greet()); // "Hi, Asha"
console.log(user instanceof User); // trueWhat if the constructor returns something?
function Primitive() {
this.value = 1;
return 42;
}
function ObjectReturn() {
this.value = 2;
return { value: 99 };
}
console.log(new Primitive().value); // 1
console.log(new ObjectReturn().value); // 99Arrow functions cannot be constructors because they do not have their own this or a prototype property. Class constructors require new; calling one without it throws.
new.target is available inside a function or class constructor. It lets code detect whether it was called with new, which is useful for backwards-compatible factory functions.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if a constructor returns an object?
- 2Why can't an arrow function be used with `new`?
- 3What is `new.target`?
- 4How would you implement `new` manually?
Say it in the interview
`new` creates a fresh object, links it to the constructor's prototype, and calls the constructor with this bound to that object. It then returns the object unless the constructor explicitly returns a different object. A returned primitive is ignored. Arrow functions cannot be constructors because they have no own this or prototype. Classes enforce new, which catches a common mistake.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.