# Constructor() in JavaScript

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661944547903/9CuZY9spn.png align="center")


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661944010892/5zmT4dBOf.png align="left")  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](https://cdn.hashnode.com/res/hashnode/image/upload/v1661944384047/94VLrhMFU.png align="center")

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1661944474282/FOV2WTfO2.png align="center")


