Understanding the “this” Keyword in JavaScript

Understanding the “this” Keyword in JavaScript

As a beginner in JavaScript, the “this” keyword can be quite daunting. You might have heard it being described as the scariest part of JavaScript or even the most confusing. Some even try to avoid it entirely because it creates so much confusion. In this article, we will attempt to decode this mystery and figure out what “this” is all about.

So, what is “this” in JavaScript? Although it might look intimidating, “this” isn’t that hard to understand. All it means is “this is the object that the function is a property of”. That’s it.

For example, if you type “this” in the developer console, you will get the window object because this gets set in our execution context as window initially. However, when it comes to coding, this part of JavaScript can be a little bit weird. Most of the time, we never want “this” to refer to the global object, but it happens all the time.

One of the pitfalls with “this” is that we unexpectedly have “this” referred to the window object when we think it should be something else. So, what can we do to avoid this? We can use the “use strict” tag. This tag was added to JavaScript as a way for us to avoid the common mistakes that can happen with JavaScript. When the language was originally designed, it wasn’t perfect, and there were bits and pieces of mistakes. But, things like “use strict” allow us to not have “this” where “this” refers to the window object. “use strict” can be added at the beginning, the first line of a function, or at the beginning of our script.

But what’s the point of the “this” keyword then? If most of the time, we don’t even care that “this” points to the global object, why did they even include “this” in the language? Well, let’s have a look at an example where “this” actually becomes useful and the reason that this keyword was created.

Let’s say we have an object with a name that is John, and John has a Date of birth. We have a function inside of this object that can return John's age “33”. But how can we access the DOB property so that this John function can calculate John’s age? We can use the “this” keyword. We can simply say “this.DOB”, and we don’t have to change anything in the function.

Here’s how you can create an object that uses the “this” keyword:

let object = {
name: "John",
DOB: 1990,
age: function() {
return `${new Date().getFullYear() - this.DOB}`;
}
}

If we run object.age(), we’ll get “33”. But if we change the DOB to 1996, we don’t have to change anything in the function. We can simply run object.age() again, and we’ll get “27”.

In conclusion, “this” can be confusing at first, but it’s an essential part of JavaScript. Understanding how “this” works will help you write better code and avoid common pitfalls.