Guide Bros

Guides about everything

Everything You Should Know About JavaScript this Keyword

JavaScript this Keyword

This time let us focus on one of the very confusing parts of JavaScript programming, the “this” keyword. So, to understand it fully, we need first to understand its usage and benefits. I find it helpful to think as I am the one who will execute the code as if I am the “index.js,” metaphorically speaking. As Mary T. Lathrap said, “You can’t understand someone until you’ve walked a mile in their shoes.”. So I want to challenge you in changing your shoes during the reading, and I hope it will be beneficial.

An Alternative Point of View

Before getting “under the hood,” first begin by thinking about executing the main js file. Inside the scopes of a project, it is usually called “index.js,” as, by default, many web servers return the file called “index.html” when just entering the name(i.e., the domain) of the web page, without specifying any particular resource(e.g., www.domain.com/aboutUs) in the URL field. Of course, this practice has nothing to do with the naming of the main JavaScript file. However, many developers currently choose to name their main file to follow the convention—anyway, enough to imitate a history class already.

The Usual Behavior of the JavaScript "this" Keyword

Just start to imagine that you see everything “index.js” sees. For example, you call many packages and libraries, invoke a few functions, and edit the DOM(Document Object Model). Then you see a function call, only this time, it uses the “this” keyword. So the critical factor here is to understand the place of the function call.

function logger(){
    console.log(this.property)
};

let anObject = {
    property: `The inner ptoperty of "anObject"`, 
    innerLogger: logger
};

property = `The window property of the "window"`;

logger();
anObject.innerLogger();

Suppose you see the instructions given in the example above. First of all, let’s understand the code line by line. Firstly, we define the function called “logger,” so it is merely a function declaration, the pure definition of the steps taken in the function. However, there is the beloved “this” keyword within. Our code snippet will most probably use it in the nearest future. Next, we define an object with two properties, a variable and the previous function.

Global Decleration

On the tenth line, there is a bit of awkward variable declaration. To make things more life-related and realistic, think about this for a second. If your lawyer says, “You have to sign this paper,” and does not define an exact place for you to sign, your job is to find the position all by yourself. As you can make a pretty usual guess based on your previous experience, the place for you to sign is at the bottom-most line of the paper. Likewise, here, you know (you being the code executor) that the default place for you to hold something is the global object if nothing is already indicating the exact ”owner” of the variable. So next time when you see something like this, you will know where to place the variable.

Further Line-by-line Execution

The next two lines tell you to invoke the functions “logger” and “anObject.innerLogger” respectively. You must know how to deal with the JavaScript “this” keyword. In the last line, the function invocation is happening through the object called “anObject”. However, on the previous line, a pure function invocation takes place.

An Important Lesson for the JavaScript "this" keyword

The most important takeaway from this article is that you always have to find the point of the function call. More importantly, we need to find the object through which the function call happens. For example, if you write code like “object.function()”, then you call your function “function” via the object “object”.

Now, we need to understand what it means to call a simple function through an object. When we execute the last line, we get the result “The inner property of anObject”. During the process, the function and the object set up a connection. That connection tells us where to find the “this”. On the contrary, when we invoke the function named “logger” without specifying the place, the “this” will point to the global object. This means that whenever you call a function in the global scope without specifying any parent object, you call it through the global object. For example, when we call the function “logger”, it is the same as to do “window.logger()”.

The Global Object

Assuming you write code for web browsers with no wrapping functions and objects, the keyword “this” will always refer to the most outer object, also called the global object. In the front end world, the global object is called “window”.

Other Global objects

There are different scenarios for the global object in different environments. Thus, we cannot state that the global object will always be the “window” whenever you encounter a JavaScript code. For example, in Node.js, the global object’s name is “global”. It is not just the naming convention, however, as the functionality also differs a lot. The “window” keeps track of what is essential for the current web page, including some functions like “isNaN”, “parseInt”, “parseFloat”, and so on. On the other hand, the “global” object in Node.js keeps track of some functionalities that are unique to itself, as” setImmediate,” “clearImeediate,” and so on.

JavaScript Scopes

Let us take a look at another example.

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

Here, it touches on scopes too. While learning about the “this” keyword, it is essential to understand the logic of scopes. For now, it is enough to realize that inner scopes(nested functions) always have access to outer ones, not the other way around. The most outer scope is called the global scope. If there is no wrapping code, it is inside the global scope. All the rest of your code has access to it.

First, we declare a variable called “self,” which is nothing but the “this” of the “func” at the given point. Moving forward, from the place we first call “this.foo” and “self.foo”, things are accessible, so we get what we expected, the same value in both places, the string “bar”.

Immediately Invoked Function Expression

Meanwhile, when creating IIFE(Immediately Invoked Function Expression), we force our code to create a new scope with its own “this”. So when calling “this.foo”, we literally can’t expect anything more, but undefined, as “foo” is not defined, and never has been, in that particular scope. However, the “foo” of “self” is available. As I mentioned previously, the inner scopes always have access to outer ones. You can find a lot of examples on the Internet.

How Does an Arrow Function Affect the JavaScript "this" keyword?

Now, it is time to get familiar with another type of functionality related to “this”. You probably remember the arrow functions that I mentioned earlier. Let us start with the fact that it is not just a syntactic sugar designed to convert ordinary functions to more readable ones, though it does. It changes the behavior of the JavaScript “this” keyword entirely. One of the most important differences is that the “this” of the arrow function is set and can’t be changed once defined. You are likely to come across the terms “dynamic” and “lexical” this. An engaging question emerges, how does one decide what scope to point out while considering an arrow function? The most appropriate explanation is that the arrow function makes the JavaScript “this” keyword refer to the “this” of the surrounding scope of its definition. Let’s look at the most famous example of the arrow function.

property =  "outer prop";
let obj = {
	property: "inner prop",
	func: () => {
		console.log(this.property)
	}
}
obj.func();

This code logs “outer prop” in the console. That is the aftermath of the arrow function using “this” keyword. As you may already guess, the object itself is not considered as a scope, here, though it is. The function is inside the object, which is inside the global scope. The scope of the “this” is the outer scope of the object, the same as the global object. These were just the main concepts; I suggest you play with the examples and come up with your examples. It is the best way to discover your knowledge gaps. I wish you the best of luck.

Make sure to check out more JavaScript tutorials.

Everything You Should Know About JavaScript this Keyword

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top