What is the purpose of the new keyword?
JavaScriptThe short answer
The new keyword creates a new object from a constructor function or class. When you call a function with new, JavaScript creates a fresh empty object, sets its prototype to the function's prototype property, runs the function with this pointing to the new object, and returns the object.
What new does step by step
function Person(name) { this.name = name;}const john = new Person('John');When new Person('John') runs, these four things happen:
- A new empty object
{}is created - The object's
__proto__is set toPerson.prototype - The
Personfunction runs withthisset to the new object - The new object is returned (unless the function returns a different object)
It is the same as doing this manually:
const john = Object.create(Person.prototype);Person.call(john, 'John');With classes
The new keyword is required with classes:
class Dog { constructor(name) { this.name = name; } bark() { console.log('Woof!'); }}const rex = new Dog('Rex');rex.bark(); // "Woof!"Calling a class without new throws an error: TypeError: Cannot call a class as a function.
What happens without new
If you forget new with a regular constructor function, this becomes the global object (window), and you accidentally create global variables:
function Person(name) { this.name = name;}const john = Person('John'); // forgot new!john; // undefined — Person returns nothingwindow.name; // "John" — accidentally set on global objectClasses prevent this mistake by throwing an error when called without new.
Interview Tip
Walk through the four steps that new performs. The key points are: it creates an empty object, sets the prototype, binds this, and returns the object. Knowing what happens when you forget new (global variable leak) shows awareness of a common bug.
Why interviewers ask this
This tests your understanding of how object creation works in JavaScript. Interviewers want to see if you know what new does under the hood, not just how to use it.