Skip to main content

Command Palette

Search for a command to run...

Constructor() in JavaScript

Published
โ€ข2 min readโ€ขView as Markdown
K

I am a seasoned Full Stack Blockchain Developer who has worked on multiple EVM chains, FLOW, and Solana Blockchain.

With a deep passion for blockchain and OSS , I have worked on numerous projects in Layer5 and Meshery, where I have been a significant contributor to the OSS community and given the honour of being a Member of Layer5.

My expertise is in JavaScript, Node.js, and other web technologies allows me to develop cutting-edge decentralized applications that are both reliable and scalable.

image.png

image.png Ever wondered what is its use or how it is used ? ๐Ÿ˜ฎ

I am here to take you through the easiest steps to understand this concept ๐Ÿ˜‰

Constructor simply put is a function to ensure that your objects are taking in the right key: value pairs.

Let me dive in an example for you

function User(){
    name="Riya";
    age=19;
    gender=female;
    if(this.age>=18){
        this.candrive=true;
    }
    else{
        this.candrive=false;
    }
}
console.log(User.candrive);

This is good right ? ๐Ÿค”

But what If there were more than 1 user like a 500 of them registering for a license test and you had to maintain all their name, age details . Chances high! that you could have missed it.

Here , comes the constructor for the rescue ๐Ÿ˜ฎ ๐Ÿ˜ฎ

function User(name,age,gender){
    this.name=name;
    this.age=age;
    this.gender=gender;
    if(this.age>=18){
        this.candrive=true;
    }
    else{
        this.candrive=false;
    }
}

Its a good practice to start constructor name with a capital letter .

So, as said before constructor is just a function here User which takes some arguments and then puts the value of the key acc to it.

Let us declare a new object using the new keyword .

let user1= new User("kamal",12,"Male");

on using this we are putting the values in the form of arguments in the constructor inorder to construct an object for us ๐Ÿค”

let us console log to see what this returns

console.log(user1.candrive);

We get the result as false isn't that cool and interesting ๐Ÿ˜ฎ But the fun and use is when you have to declare more object of the same type like ->

let user2= new User("amir",27,"Male");
let user3= new User("anil","Male");
let user4= new User("tarun",23,"Male");
let user5= new User("kamal",12,"Male");

console logging all of them will give

image.png

Notice- how undefined is returned wherever the data is not provided to the constructor.

That was all from my side , Thank you ... Don't miss to like
image.png