"new" Keyword, Decoded🔥✨

"new" Keyword, Decoded🔥✨

How Does ‘new’ Keyword work in JS?

Welcome❤️‍🔥

to the Interactive🤗 Blog on the "new" Keyword!

In this blog post, we'll explore the "new" keyword in JS and understand its usage with code examples.

The purpose of this article is to show how the “new” keyword makes our lives much easier.

Let's dive in!

Normal Function Call🙂

Consider a function called createUser, which is responsible for creating user objects with properties like name, course, and age based on the given parameters.

function createUser(name = "", course = "", age = 0) {
    const user = {};
    user.name = name;
    user.course = course;
    user.age = age;
    return user;
}

const exampleUser = createUser('Manvith', 'JavaScript', 20);
console.log(exampleUser); // { name: 'Manvith', course: 'js', age: 20 }

In this case, we manually create an object, assign properties, and return it from the function.

How does "new" help us?🤔

Now, let's see how the "new" keyword can make object creation simpler. We'll create a constructor function, conventionally named with a capital letter (e.g., UserConstructor), which will achieve the same result as the createUser function above.

function UserConstructor(name = "", course = "", age = 0) {
    this.name = name;
    this.course = course;
    this.age = age;
}

const exampleUser = new UserConstructor('Manvith', 'JavaScript', 20);
console.log(exampleUser); 
// UserConstructor { name: 'Manvith', course: 'JavaScript', age: 20 }

Using the "new" keyword, we can now directly invoke the constructor function and get the desired object without explicitly creating an object and returning it.

What happens behind the scenes?🧐

When we use the "new" keyword to invoke a constructor function, several implicit steps occur behind the scenes:

  1. Creates an empty object.

  2. Binds the empty object to the this value within the constructor function.

  3. The function's prototype becomes the prototype of the new object.

  4. If there is no explicit return statement in the constructor, the "new" keyword implicitly returns this.

Here's some pseudocode to help visualize what happens:

 "use strict";

function UserConstructor(name, course, age) {
    /**
     * What happens behind the scenes when we invoke with the "new" keyword:
     *
     * this = {};
     * this.__proto__ = UserConstructor.prototype;
     *
     */
    this.name = name;
    this.course = course;
    this.age = age;
    /**
     *
     * If we haven't returned an object, array, or function, the "new" keyword implicitly returns "this."
     * If we try to return anything except an object, array, or function, it will return "this" (the scoped object).
     * i.e. return "I am a string" would still return "this."
     *
     * return this;
     */
}

const exampleUser = new UserConstructor('Manvith', 'JavaScript', 20);
console.log(exampleUser);

Calling a non-constructor with "new"🤫

What happens if we accidentally use the "new" keyword with a regular function like createUser? Let's find out.

const exampleUser = new createUser('Manvith', 'JavaScript', 20);
console.log(exampleUser); // { name: 'Manvith', course: 'JavaScript', age: 20 }

The "new" keyword is still applied, but since we're not using this inside the function and we explicitly return an object, the output remains the same. The "new" keyword's implicit behavior doesn't significantly impact this case.

In conclusion, the "new" keyword is a powerful tool when used correctly with constructor functions. It simplifies object creation by handling the behind-the-scenes steps for us.

I hope you found this explanation useful! If you want to learn more about the "this" keyword or other programming concepts, feel free to check out my other articles. 🤗 if you enjoyed reading this, feel free to follow me 💗

Happy coding! 💻