The new operator
Syntax
const obj = new Constructor(...args);Constructor- a function or class invoked withnew;...args- the arguments passed to the constructor;- the result - a new object built from the constructor's template.
What new does under the hood (step by step)
When you write:
const user = new User('Oleh');The engine performs four steps:
1. A new empty object is created
const obj = {};2. The prototype is set
The new object gets a reference to the constructor's prototype:
obj.__proto__ = User.prototype;This means obj inherits methods from User.prototype.
3. The constructor itself runs
The User function is called, and inside it, this points to the new object:
const result = User.call(obj, 'Oleh');4. The object is returned
If the constructor manually returns an object → that object is returned.
Otherwise → the obj created in step 1 is returned.
return typeof result === 'object' ? result : obj;Example with a constructor function
function User(name) {
this.name = name;
this.isAdmin = false;
}
const user = new User('Oleh');
console.log(user.name); // "Oleh"
console.log(user.isAdmin); // falseWithout
new,thiswould point towindow(in a browser) orundefined(in strict mode). That's why it's important to always call constructors withnew.
Example with a class
class Car {
constructor(model) {
this.model = model;
}
drive() {
console.log(`${this.model} is driving`);
}
}
const tesla = new Car('Tesla');
tesla.drive(); // "Tesla is driving"Classes are just syntactic sugar over constructor functions. Under the hood,
newworks exactly the same way.
Example with a returned object
If a constructor function manually returns an object,
it replaces the result of new:
function User(name) {
this.name = name;
return { name: 'Overridden' };
}
const u = new User('Oleh');
console.log(u.name); // "Overridden"If a primitive is returned, it is ignored:
function Product(name) {
this.name = name;
return 123; // ignored
}
const p = new Product('Phone');
console.log(p.name); // "Phone"Example without new
function Animal(name) {
this.name = name;
}
const a1 = Animal('Cat'); // called without new
console.log(a1); // undefined
console.log(globalThis.name); // "Cat" - got written into the global scopeSo always call constructors with
new, or add a safeguard inside the function:
function Animal(name) {
if (!(this instanceof Animal)) {
return new Animal(name);
}
this.name = name;
}Use with built-in constructors
const date = new Date();
const reg = new RegExp('\\d+');
const arr = new Array(3); // [ <3 empty items> ]
const obj = new Object(); // {}Almost all built-in classes (
Date,Map,Set,Error,RegExp,Promise) requirenew.
Summary
| Step | What new does |
|---|---|
| 1 | Creates a new empty object |
| 2 | Sets the prototype obj.__proto__ = Constructor.prototype |
| 3 | Calls the constructor with this = obj |
| 4 | Returns the object (or whatever the constructor returns) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.