Javascript’s “new” Keyword Explained as 
                                   Simply as Possible

Javascript’s “new” Keyword Explained as Simply as Possible

How Exactly Does the ‘new’ Keyword work in JavaScript?

Hello Readers!👋🏻

Let me introduce you all with something new 😁today!

There are many powerful keywords in programming languages and programmers don’t make much from them as they misunderstand them. For example, the “this” keyword in JavaScript is a very powerful keyword. I highly recommend you to read my article on the topic:This keyword

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

Normal Function Call🙂

To explain what new does, let’s start with just a normal function, called without new. We want to write a function that will create "user" objects. It’ll give these objects name, course, and age properties based on the parameters that it takes in.

Let’s use a very classic example.

function createUser(name = "", course = "", age = 0) {

    const user = {};    

     user.name = name;
     user.course = course;
     user.age = age;
    return  user ;
}
const exampleUser=createUser('Hitesh', 'js', 31);
console.log(exampleUser);  // { name: 'Hitesh', course : 'js' age: 31 }

We created an object, assign properties, and return it at the end.

How does "new" can help us?🤔

Let’s create a function that does the same thing, but we want it to be invoked using new. This function will create the same object as the one above.

We can create a constructor function — the convention is to start the function's name from the capital letter i.e. **UserConstructor** and not userContructor. It will work in both cases, however.

function UserConstructor(name = "", course = "", age = 0) {
  this.name = name;
  this.course  = course ;
  this.age = age;
}
const exampleUser = new  UserConstructor("Hitesh", "js", 31);
console.log(exampleUser);
// UserConstructor {name: "Hitesh", position: "js", age: 31}

Invoking createUser normally and invoking UserConstructor with new both result in the same object being created. What’s going on?🙄

hi.png

If you take a look inside the function UserConstructor you will notice that there is no return statement, nor there is no object creation at the beginning, yet still, we get the desired result.

This happens thanks to the 😌 new keyword, as it adds some implicit behavior that we do not see i.e.

  • Creates an empty object.
  • The empty object is binded to this value.
  • The function will inherit from functionName.prototype.
  • Returns this if no explicit return statement is used.

Here is pseudocode to inspect what happens behind the scenes when we invoke the function with a new keyword


"use strict";

function UserConstructor(name, course , age) {
  /**
   * What is happening behind the scenes when we invoke with "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 object, array or function, return this (the scoped 
      object)
   * i.e. return "I am string" would still return this
   *
   * return this;
   */
}
const exampleUser= new UserConstructor("Hitesh", "js", 31);
console.log(exampleUser;

There is some technical jargon above i.e. __proto__and prototype.

If you aren’t familiar with constructors or prototypes, don’t worry about it too much for now. You’ll run into them sooner or later.

The important thing is, that the new object implicitly returned by the constructor function will be able to inherit properties and methods.

If the keyword this is confusing for you, I’ve got an article for you where I explain it in simple terms.This keyword

What happens if we call a non-constructor with new?🤫

What happens if we invoke a normal function like createUser using new? Nothing special. The same rules apply. in the case of createUser, we see nothing explicitly happening.

const exampleUser = new createUser('Hitesh', 'js, 31);
console.log(exampleUser);// -> { {name: 'Hitesh', course: 'js', age: 31} }

Why?🤔 Let’s add our implicit code in to createUser.

function createUser(name,course, age) {
    // this = {};
    // this.constructor = UserConstructor;
    // this.__proto__ = UserConstructor.prototype;
    // Set up the logic such that: if there is a return statement
    // in the function body that
    // returns anything EXCEPT an
    // object, array, or function:
    //     return this (the newly
    //     constructed object)
    //     instead of that item at
    //     the return statement;
    var userObj = {};
    userObj.name = name;
    userObj.course= course;
    userObj.age = age;

    return userObj;

    // return this;
}

The implicit code is still added in:

  • It binds this to a new object and sets its constructor and prototype.
  • It adds logic that will return this instead of a non-object.
  • It adds an implicit return this statement at the end.

This doesn’t affect our code, since we don’t use this keyword in our code. We also explicitly return an object, userObj, so the returning logic and the return this line have no use.

Effectively, using new to invoke our function here has no effect on the output. If we were using this or if we weren’t returning an object, the function would have different effects when invoked with and without new.

If this was useful, please hit the heart and feel free to follow and read my other articles.🤗

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!