The new keyword in javascript

The new keyword in JavaScript!

The new keyword is used to create a new instance of an object, and it's a fundamental concept in JavaScript. When you use new with a constructor function, it does several things:

  1. Creates a new object: new creates a new, empty object that inherits from the prototype of the constructor function.
  2. Calls the constructor function: new calls the constructor function, passing the new object as the this context.
  3. Sets the this context: The this context is set to the new object, allowing the constructor function to initialize the object's properties.
  4. Returns the new object: The new keyword returns the new object, which is assigned to the variable specified in the new expression.

Here's an example:

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

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

In this example, new creates a new object, calls the Person constructor function, sets the this context to the new object, and returns the new object, which is assigned to the person variable.

Some important notes:

Common use cases for new include: