How new keyword work in JavaScript

BhupendraBhupendra
4 min read

In JavaScript, the new keyword is used to create an instance of an object from a constructor function or a class. When you use the new keyword, it performs several actions behind the scenes to initialize the newly created object. Here's how the new keyword works step by step.

How new Works ?

  1. Creates a new empty object: When you call a function with new, it creates an empty object that will eventually be linked to the prototype of the constructor function.

  2. Sets the prototype of the new object: The newly created object's __proto__ (prototype) is linked to the constructor function's prototype property. This allows the new object to inherit methods and properties from the constructor’s prototype.

  3. Binds this to the new object: Inside the constructor function, the this keyword is bound to the newly created object. This allows the constructor to assign properties and methods to this, which ultimately references the new object.

  4. Executes the constructor function: The constructor function is executed with this bound to the new object. Any properties or methods defined in the constructor function will be assigned to the new object.

  5. Returns the new object: By default, the new keyword returns the new object unless the constructor explicitly returns a different object.

Example: Using new with a Constructor Function

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
  this.drive = function() {
    console.log(`Driving a ${this.brand} ${this.model}`);
  };
}

const myCar = new Car('Toyota', 'Corolla');
myCar.drive();  // Output: Driving a Toyota Corolla

Here’s what happens when new Car('Toyota', 'Corolla') is called:

  1. Step 1: An empty object is created: {}.

  2. Step 2: The empty object’s __proto__ is set to Car.prototype.

  3. Step 3: this is bound to the new object, and the properties brand and model are added to the new object.

  4. Step 4: The Car function runs, and the drive() method is added to the object.

  5. Step 5: The newly created object (myCar) is returned, which now has brand, model, and drive().

Example: Using new with ES6 Classes

In ES6, classes provide a cleaner syntax for creating objects using new. However, behind the scenes, they work similarly to constructor functions.

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  drive() {
    console.log(`Driving a ${this.brand} ${this.model}`);
  }
}

const myCar = new Car('Tesla', 'Model 3');
myCar.drive();  // Output: Driving a Tesla Model 3

In this example:

  • The new keyword is used to create an instance of the Car class.

  • It follows the same process of creating a new object, binding this, setting up the prototype, and returning the new object.

Returning Values from Constructors

Normally, a constructor function returns the newly created object. However, if you explicitly return an object from the constructor, that object will be returned instead of the new instance.

function Person(name) {
  this.name = name;

  // Explicitly returning an object
  return {
    age: 30
  };
}

const person = new Person('John');
console.log(person);  // Output: { age: 30 }

In this case, even though we passed the name 'John', the returned object is { age: 30 } because the constructor returned an object explicitly. If no object is explicitly returned, the new object created with new is returned.

What Happens Without new?

If you call a constructor function without new, this will refer to the global object (in non-strict mode), or be undefined (in strict mode), which can lead to unexpected behavior.

function Car(brand) {
  this.brand = brand;
}

const car1 = new Car('Toyota');  // Works as expected
console.log(car1.brand);  // Output: Toyota

const car2 = Car('Honda');  // Forgetting `new`
console.log(car2);  // Output: undefined (because the function returns nothing)

console.log(window.brand);  // Output: Honda (in non-strict mode, `this` refers to the global object)

Without new, the Car function will run like a normal function, and this.brand will point to the global object (window in browsers). This is why using new is crucial when creating instances with constructors.

Summary

The new keyword in JavaScript:

  1. Creates a new object.

  2. Links the new object's prototype to the constructor's prototype.

  3. Binds this to the new object within the constructor.

  4. Executes the constructor to initialize the object.

  5. Returns the new object by default.

This is the process that allows you to create new objects in JavaScript based on constructors or classes.

0
Subscribe to my newsletter

Read articles from Bhupendra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bhupendra
Bhupendra

I'm a passionate software developer with a strong foundation in JavaScript, TypeScript, Node.js, and React. I've honed my skills in full-stack development and building scalable, user-friendly applications. I'm driven by creating innovative solutions that solve real-world problems and enhance user experiences. I'm a quick learner, constantly updating myself with the latest industry trends and best practices. Beyond technical skills, I value collaboration, problem-solving, and maintaining a growth mindset. I'm excited to contribute my expertise to a dynamic team and make a positive impact through technology.