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, bindsthis
, and returns it.) -
How is
new
different fromObject.create()
?
(Answer:new
calls a constructor, whileObject.create()
directly sets a prototype.) -
Can arrow functions be used with
new
?
(Answer: No, they lack their ownthis
binding.)
Best Practices
- Always use
new
with constructor functions. - Follow PascalCase naming for constructors (e.g.,
function User()
). - Use ES6
class
syntax (which internally usesnew
).
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.