Intermediate JavaScript Interview QuestionsIntermediateConcept
JavaScript · Question 41
What does the new operator do when you call a constructor in JavaScript?
Direct answer
new creates an object linked to the constructor’s prototype, calls the constructor with that object as this, and normally returns the new object unless the constructor explicitly returns another object.
A simplified mental model for new User("Ada") is: create a fresh object, connect its internal prototype to User.prototype, invoke User with the new object as this, then return the appropriate construction result.
- If the constructor returns no value or returns a primitive, the newly created instance is returned.
- If the constructor explicitly returns an object (including a function object), that object can become the result instead of the automatically created instance.
- The prototype connection is why instances can access methods placed on
User.prototypewithout storing separate method copies on each instance.
This is also why calling a traditional constructor without new can behave very differently: it becomes an ordinary function call rather than construction. JavaScript class constructors prevent that mistake by requiring construction.