What is the new JavaScript keyword, and how does it work?

What is the new JavaScript keyword, and how does it work? Why is it needed, and what problems does it solve? When should you use it, and when is it not appropriate?

The new javascript keyword is used with a constructor function to create an instance of an object. It performs four steps:

  1. Creates a new empty object.
  2. Sets the this keyword inside the constructor to reference the new object.
  3. Links the new object to the constructor’s prototype.
  4. Returns the new object.
function Car(model, year) {
this.model = model;
this.year = year;
}

In this example, new creates an instance of Car with its own model and year properties.

The new javascript keyword solves the problem of creating multiple instances of objects with shared methods and properties, without duplicating the logic in each instance. Without new, you would have to manually set up the object and its properties.

function Car(model, year) {
this.model = model;
this.year = year;
}
const car1 = new Car("Honda", 2021);
const car2 = new Car("Ford", 2020);

Using new ensures all instances of Car share the same prototype methods, reducing redundancy.

It is appropriate to use new javascript when you need to create multiple instances of an object, such as when using constructor functions or classes. However, avoid using new with regular functions or in scenarios where you’re not intending to create an object.

// Appropriate use
const person = new Person("Alice");
// Not appropriate
const sum = new Math.add(1, 2); // Wrong, use Math.add(1, 2) directly