Loading...

What is “this” in JavaScript? Complete guide to this keyword

What is “this” in JavaScript? Complete guide to this keyword

In one of the previous blog posts, you learned about the Object Data Type in JavaScript. Let’s recap the code below:

let student = { name: "Jason Bourne", age: 22, gender: "male", college: "Harvard", hobbies: ["Coding", "Breaking computers"], birthPlace: "USA", dateOfBirth: "Jan 1, 2000", }
Code language: JavaScript (javascript)

All of these are values that are either of the Number, String, or Array data type. You have already learned about functions in JavaScript. If you need to jog your memory, read this blog!

The question is, can a Object data type have a function as a value?

What are Methods in JavaScript?

In the blog on Arrays in JavaScript, you learned to add a new element to an array using push! Let us add another hobby, “Reading” in the student object.

Pushing to an Array
Click here to get the code

As you can observe in the output, “Reading” has been added to the hobbies array, and you used the push method to use it!

So a method is just a function, but it relates to a specific object! What if I ask you to print the name of the student in upper case on the console? You will have to use the toUpperCase() method!

student.name.toUpperCase()
Code language: JavaScript (javascript)

The next logical question is, can you define a method on an Object you created? And the answer is yes!

Let us say that you want to print the hobbies in a separate line, by calling printHobbies() method on student.

If you define a function (not a method!) outside student to do this, it will look something like this:

function printHobbies(){ for (let i = 0; i < student.hobbies.length; i++) { console.log(student.hobbies[i]) } }
Code language: JavaScript (javascript)

To add this as a method to the student Object, you don’t have to change much:

let student = { //----code-snip----------------------------- dateOfBirth: "Jan 1, 2000", printHobbies: function() { for (let i = 0; i < student.hobbies.length; i++) { console.log(student.hobbies[i]) } } }
Code language: JavaScript (javascript)

To call this method on student, you have to use the dot operator, followed by the name of the key, which in this case is printHobbies. This part is just like accessing a key inside an Object.

It should be followed by () to actually call the method! The final output will look like this:

Method in an Object
Click here to get the code

Notice carefully, the function keyword doesn’t need a name inside the Object. It will use the name of the key, printHobbies as function name.

Right now, in the printHobbies method, we are accessing each element of the hobbies array by its index. As is evident, the code is long and verbose for something very easy. JavaScript provides a method on the Array Data Structures called forEach. The refactored code will look much cleaner while giving the same output!

forEach in JavaScript
Click here to get the code

I have replaced the for loop and indices with the method forEach. Let’s quickly study this method of Arrays:

forEach in JavaScript
Click here to get the code

Given arr, the forEach method, takes a function as an argument! It has access to three values:

  • Current Value of the Array
  • Current Index of the Array
  • The Array itself

So for every value in the array, forEach will provide access to these three values. You can choose to use all three of these values or any one of them. In the student example, we are just using the currentValue.

The curious among you can try to change the function taken as a parameter by the forEach method into an arrow function which we saw in the last blog. The final Object will look like this:

let student = { name: "Jason Bourne", age: 22, gender: "male", college: "Harvard", hobbies: ["Coding", "Breaking computers"], birthPlace: "USA", dateOfBirth: "Jan 1, 2000", printHobbies: function() { student.hobbies.forEach(h => console.log(h)) } }
Code language: JavaScript (javascript)

I will be using this code going forward in the blog.

this keyword in JavaScript

Look carefully, in the printHobbies method of the student Object, we are writing,

student.hobbies.forEach(...)
Code language: JavaScript (javascript)

What if I were to change the name of the object from student to user later? I would have to also update the printHobbies method. Now imagine if I have 100 such students who have to be changed to users. I would have to make 100 changes just so that the code doesn’t break!

Well, as always there had to be an easier way! And there is. Replace:

student.hobbies.forEach(...) // With this.hobbies.forEach(...)
Code language: JavaScript (javascript)

The output will remain exactly the same!

this in JavaScript
Click here to get the code

But now, you don’t have to worry about updating the printHobbies method if you change student to user!

So this keyword will give you access to the object it is placed inside! You don’t have to refer to the object by its name anymore.

The experimental among you must be itching to convert function() to an arrow function!

let student = { //---code-snip---------------------------- printHobbies: function() { this.hobbies.forEach(h => console.log(h)) } } // TO let student = { //---code-snip---------------------------- printHobbies: () => { this.hobbies.forEach(h => console.log(h)) } }
Code language: JavaScript (javascript)

Let’s try it out!

this with Arrow Function
this with Arrow Function

You will get an error! It says that forEach is undefined for the object we are trying to call it on! But why? What changed?

The scope did! You can learn more about the basics of scoping in this blog.

When you defined the method with the function keyword, the value of the this keyword was set to the Object (in this case student) it was being called from.

But when you change to an arrow function, the value of this is set to the scope it is called from! Let’s check the what is the Object that the this keyword is being set to with the arrow function:

this in JavaScript
this in JavaScript

The output for both lines 10 and 18 is the Window object. A Window Object refers to your browser window. We will discuss more on this when we reach DOM manipulation.

But as per line 10, it is clear that since it is referring to the Window object, which doesn’t have any hobbies array, we get a TypeError!

So to use this keyword inside an object method, we should only use the the function keyword.

One last thing you can do to reduce verbosity is omitting the colon(:) and simply add a standalone method without it being a key-value pair as follows:

let student = { //----code-snip------------------------------ dateOfBirth: "Jan 1, 2000", printHobbies() { this.hobbies.forEach(h => console.log(h)) } }
Code language: JavaScript (javascript)

Conclusion

You learnt a lot about methods in this blog. You created your own custom method and explored the forEach method for arrays in detail.

You also say when to use the arrow function and how an arrow function affects the this keyword.

In the next blog, we will delve deeper into JavaScript Objects and how to create constructors so that you can use the new keyword to easily create multiple student objects. See you then!

Sharing is caring

Did you like what Rishabh Mittal wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far