0
0
JavascriptConceptBeginner · 3 min read

What is the new keyword in JavaScript and How It Works

The new keyword in JavaScript creates a new object from a constructor function or class. It sets up the new object’s properties and links it to the constructor’s prototype, allowing you to build multiple similar objects easily.
⚙️

How It Works

Think of the new keyword as a factory machine that builds new objects for you. When you use new with a constructor function or class, JavaScript does three main things: it creates a fresh empty object, sets up that object to inherit from the constructor’s prototype, and then runs the constructor function to fill the object with properties and methods.

This is like ordering a custom toy from a factory. The factory first prepares a blank toy, then decorates it based on your instructions. The new keyword automates this process so you don’t have to create each object manually.

💻

Example

This example shows how to use new with a constructor function to create multiple person objects with their own names and ages.
javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const alice = new Person('Alice', 30);
const bob = new Person('Bob', 25);

console.log(alice.name); // Alice
console.log(bob.age);   // 25
Output
Alice 25
🎯

When to Use

Use the new keyword when you want to create multiple objects that share the same structure and behavior. It is especially useful when working with constructor functions or classes to build objects like users, products, or any repeated data type.

For example, in a game, you might use new to create many enemy characters with similar properties but different names and strengths. This saves time and keeps your code organized.

Key Points

  • new creates a new object from a constructor or class.
  • It links the new object to the constructor’s prototype for shared methods.
  • The constructor function runs to initialize the new object’s properties.
  • Without new, the constructor won’t create a new object properly.

Key Takeaways

The new keyword creates and initializes new objects from constructors or classes.
It sets up inheritance by linking the new object to the constructor’s prototype.
Use new to build multiple similar objects easily and cleanly.
Always use new when calling constructor functions to avoid errors.