Using the JavaScript Keyword new

The new keyword in JavaScript is used to create an instance of an object or a specific data type. It works with constructors, which are special functions designed to initialize an object. When you use the new keyword, it sets up a new object, runs the constructor function, and returns the new object.

How Does It Work?

When you use the new keyword, a few things happen behind the scenes:

  1. Create a New Object: A new, empty object is created.
  2. Link to Prototype: The new object is linked to the prototype of the constructor function.
  3. Bind this: The constructor function is called with this pointing to the newly created object.
  4. Return the Object: If the constructor doesn’t explicitly return an object, the new object is returned by default.

Key Points

  • The new keyword is used to create objects based on constructors.
  • When you create an object with new, JavaScript automatically handles linking prototypes and setting up inheritance.

Examples

Creating a Custom Object with a Constructor

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

let myCar = new Car('Toyota', 'Corolla', 2021);
console.log(myCar);

In this example, the Car function is a constructor. When we use new Car(...), it creates an instance of Car and assigns the properties make, model, and year.

The output will be:

  Car { make: 'Toyota', model: 'Corolla', year: 2021 }

Using new with Built-in Constructors

The new keyword can also be used with JavaScript’s built-in constructors, like Object, Array, or Date.

let today = new Date();
console.log(today);

This creates a new instance of the Date object, representing the current date and time.

Another example is using new with Array:

let numbers = new Array(5);
console.log(numbers);

This creates an empty array with a length of 5. Note that this only creates space for five items, without actually filling them.

Practical Tips

Custom Constructors: When creating custom objects, use new with constructor functions to ensure each instance has the properties and methods defined by the constructor.

  function Person(name, age) {
    this.name = name;
    this.age = age;
  }

  let person1 = new Person('Alice', 30);
  console.log(person1.name); // Output: 'Alice'

Prototype Methods: To avoid duplicating methods for each instance, use the prototype property. For example:

  Car.prototype.startEngine = function() {
    console.log(`${this.make} ${this.model} is starting...`);
  };

  myCar.startEngine(); // Output: 'Toyota Corolla is starting...'

The startEngine method is added to Car‘s prototype, meaning all instances of Car will share this method without duplicating it in memory.