JavaScript Interview Question #107
What does the new operator do in JavaScript?
Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate
Quick Interview Answer
When used with a constructable function or class, new creates a new object, links it to the constructor's prototype, calls the constructor with this bound to the new object, and normally returns that object.
Detailed Explanation
When used with a constructable function or class, new creates a new object, links it to the constructor's prototype, calls the constructor with this bound to the new object, and normally returns that object.
If a constructor explicitly returns another non-primitive object, that object can become the result instead. Modern code often uses class syntax, but understanding new is important because classes are built on JavaScript's prototype model.
Code Example
function Product(name, price) {
this.name = name;
this.price = price;
}
Product.prototype.describe = function () {
return `${this.name}: $${this.price}`;
};
const product = new Product("Keyboard", 50);
console.log(product.describe());