What is Constructor in JavaScript?
Hey Folks! As you know, we are doing a JavaScript blog series. So I am attaching all the blogs you will need to read or at least have an understanding of to reach this point:
- What Is const and let in Javascript? JS Variables and Data Types
- JavaScript Operators – Complete Guide With Examples
- Type Conversion & Arithmetic Operators in JavaScript
- JavaScript if/else statements – JS Conditional Statements
- Arrays in JavaScript: Complete Guide With Examples [2022]
- Loops in JavaScript: for and while loops
- How to write a JavaScript function? Complete guide to functions in JavaScript
- What is scoping and hoisting in JavaScript? Levels of scoping in JS
- What is “this” in JavaScript? Complete guide to this keyword
So if you need a refresher, now you have an index! At any time you want to code alongside, fire up a codedamn playground, which is a powerful IDE baked right into your browser.
The Situation
Remember the student
object from the last blog? I’ll put a simplified version below:
let student = {
name: "Rishabh",
age: 23
}
Code language: JavaScript (javascript)
What if you have to create 100 different students just like this and make sure that each one of them has a name
and age
property? The possibility of error, that you will skip a field becomes very heavy.
To solve this we have constructor functions in JavaScript, which is what we will learn today.
Simple Student Constructor
Well, since the constructor function is still a “function”, it will be defined using the function
keyword.
function Student() {
this.name = "Rishabh",
this.age = 23
}
Code language: JavaScript (javascript)
Note carefully, how the “function name” begins with a capital “S” and not a small “s”. It is a good practice to keep the first letter of a constructor function capital.
Inside the curly braces, the name
and age
have been added after this.
. Recall from the previous blog, that this
paired with function
keyword refers to the current local scope of Student
.
But how do you use this?
To do that you will have to create an Object of Student
using the new
keyword as below:
let student = new Student()
Code language: JavaScript (javascript)
This might look a little greek. But bear with me you will get the hang of this. The LHS is simply creating a variable student
using let
. On the RHS side, calling new
on Student
actually creates an Object that contains the name “Rishabh” and age 23. The output is below:
You get Student
with key-value pairs for the name and age. In fact, you can access the name and age values like student
was defined as an object using the way previously seen.
console.log(student.name) // Rishabh
console.log(student.age) // 23
Code language: JavaScript (javascript)
This method of creating new objects is called object literals. Try this out:
function Student() {
this.name = "Rishabh",
this.age = 23
}
let student1 = new Student()
let student2 = new Student()
Code language: JavaScript (javascript)
It will create 2 different objects, student1
and student2
. But the issue is both of them will have the name Rishabh and the age as 23.
The name and age are called properties or attributes of the Student
constructor.
That isn’t very helpful, right? If only we could give custom names and ages!
Arguments for Constructor Functions
Well, constructors after all are a type of function. So they can take arguments too. You simply have to add them in (arg1, arg2)
the round brackets and use them inside the constructor body:
Instead of hardcoding “Rishabh” and 23, the constructor now takes two arguments, name
and age
that are being used inside the body to set values for attributes this.name
and this.age
.
The argument names can be anything. Even the below would work:
function Student(x, y) {
this.name = x,
this.age = y
}
let student1 = new Student("Rishabh", 23)
console.log(student1)
let student2 = new Student("Mehul", 24)
console.log(student2)
Code language: JavaScript (javascript)
Another change is, that while creating a new object, we now have to pass the values for name and age explicitly. If we don’t do that, JavaScript will initialize them as undefined
. But this gives us an opportunity to update these values anytime later we wish to like shown below for student3
:
This is especially useful when you don’t know what values to assign to the attributes while creating the object.
But keeping values undefined
is not necessarily a good decision. It can lead to unexpected errors later on. So you can default values:
function Student(name="NA", age=-1) {
this.name = name,
this.age = age
}
let student3 = new Student()
console.log(student3.name) // NA
console.log(student3.age) // -1
Code language: JavaScript (javascript)
Creating Arrays Using new
I understand that this approach of creating a new Object from a constructor function can take time to digest. So, I recommend you watch this 1-minute video, where we create arrays using the same technique. The familiarity with arrays will help you get adjusted to the new syntax.
Exercise
Try to complete this task now:
- Create a constructor
User
- It should have the following properties:
- name
- age
- gender
- Implement a method inside the constructor that checks if the user is eligible to drive or not. Do not worry, the way to do this is exactly the same as defining a method on an object! Or you can refer to this blog to learn how: What is “this” in JavaScript? Complete guide to this keyword
- Create 2 users with the following parameters:
- User 1:
- name: “Rishabh”
- age: 23,
- gender: “Male”
- User 2:
- name: “Mehul”
- age: 17
- gender: “Male”
- User 1:
- Call the method that checks eligibility to drive or not!
Once done, check the answer below:
function User(name, age, gender) {
this.name = name
this.age = age
this.gender = gender
this.eligibleToDrive = function() {
if (this.age >= 18) {
console.log("Eligible to drive!")
} else {
console.log("Not eligible to drive!")
}
}
}
let u1 = new User("Rishabh", 23, "Male")
u1.eligibleToDrive()
let u2 = new User("Mehul", 17, "Male")
u2.eligibleToDrive()
Code language: JavaScript (javascript)
Conclusion
You learned in-depth about the new
keyword and how it is useful to create objects in JavaScript, especially for objects created by you. You also created custom objects of your own by looking at constructor functions.
The next blog will extend this knowledge into something called prototypes and prototypal inheritance. See you then!
Sharing is caring
Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: