Javascript new

The new keyword in JavaScript!

The new keyword is used to create a new object from a constructor function. When you use new with a constructor function, it does several things:

  1. Creates a new object: new creates a new, empty object that is a 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 prototype property: new sets the prototype property of the new object to the prototype of the constructor function.
  4. Returns the new object: new returns the new object.

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 person and calls the Person constructor function, passing John and 30 as arguments. The constructor function sets the name and age properties on the new object, and new returns the new object.

Why use new?

Using new with a constructor function has several benefits:

  1. Creates a new object: new ensures that each time you create an object, it's a brand new, independent object.
  2. Sets up the prototype chain: new sets up the prototype chain for the new object, which allows you to use prototype methods and properties.
  3. Returns the new object: new returns the new object, making it easy to assign it to a variable or use it in your code.

Common mistakes

Here are some common mistakes to avoid when using new:

  1. Forgetting new: If you forget to use new with a constructor function, it will return the constructor function itself, rather than creating a new object.
  2. Not using new with a constructor function: If you use new with a non-constructor function, it will throw an error.