What is the new
Keyword Used for in JavaScript?
The new
keyword in JavaScript is used to create an instance of an object from a constructor function. It initializes a new object and binds this
to it, enabling object-oriented programming (OOP) in JavaScript.
How new
Works
When you use new
with a function, four key things happen:
- Creates a new empty object (
{}
).
- Sets the prototype of this object to the constructor’s
prototype
.
- Binds
this
to the new object inside the constructor.
- Returns the object (unless the constructor returns a different object).
Example: Constructor Function with new
function Car(make, model) {
this.make = make;
this.model = model;
}
const myCar = new Car('Toyota', 'Camry');
console.log(myCar.make); // Output: "Toyota"
Here, new Car()
creates an object with make
and model
properties.
What Happens Without new
?
If you forget new
, this
refers to the global object (or undefined
in strict mode), leading to bugs:
const badCar = Car('Honda', 'Civic'); // ❌ No `new`
console.log(badCar); // undefined
console.log(window.make); // "Honda" (leaks to global scope!)
Common Interview Questions
-
What does new
do under the hood?
(Answer: Creates an object, sets prototype, binds this
, and returns it.)
-
How is new
different from Object.create()
?
(Answer: new
calls a constructor, while Object.create()
directly sets a prototype.)
-
Can arrow functions be used with new
?
(Answer: No, they lack their own this
binding.)
Best Practices
- Always use
new
with constructor functions.
- Follow PascalCase naming for constructors (e.g.,
function User()
).
- Use ES6
class
syntax (which internally uses new
).