The Truth About `new` Keyword in JavaScript
What are we gonna Study?
Hey there folks, hope you are doing great and having fun in your dev life!
So, today we'll discuss about the following topics:
What the
newkeyword doesConstructor functions
Object creation process
How
newlinks prototypesInstances created from constructors
As always you'll gain knowledge within a few minutes, Gather all your focus here (don't focus on your crush) and bear with me till the very end of it...
Pre Requisites
Before we start here is the list of pre-requisites along with my blogs on them which you can read if you want:
thiskeyword - Click herebind, call, apply - Click here
OOPS - Click here
What The new Keyword Does?
The new keyword creates an instance of a user-defined class or the built-in classes like (Error, Array, Date) that has a constructor function.
Basically it creates an instance of a class.
Here is an example:
class Character {
constructor(name, jutsu) {
this.name = name;
this.jutsu = jutsu;
}
introduce() {
console.log(`Hi, I'm \({this.name} and my jutsu is \){this.jutsu}.`);
}
}
const itachi = new Character("Itachi Uchiha", "Amaterasu");
Here, we can see that the new keyword created an instance of Character class.
Don't worry about how it does? We will discuss that, just have some patience :)
Object Creation Process
When you use new keyword, The JavaScript engine goes through a process which generally have 4 steps, let's discuss about them.
1. Creation of Plain Object
- In this step, it creates an empty object.
2. Setting Prototype
It links the prototypes of the object with the prototypes of the constructor.
This makes a chain of inheritance, thus allowing this newly created object to access methods in constructor's prototype.
3. Binds this
The constructor function is executed using
thiskeyword on our newly created object.Basically, in this step the values are filled inside the object (the values you are passing).
4. Returns Object
Now, it finally returns the object.
Funfact: It's done implicitely (automatically).
Here is a visual diagram of the flow
Wrap Up!
Pretty short, wasn't it?
Infact, the shortest i've ever wrote, but that is it, all the 5 topics has been covered and congratulations you finally know how new works :)
That is it for today, I'll catch you up in the next blog until then keep coding and sipping tea/coffee ☕💝

