JavaScript: this is easy and what do you need to know about it!

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
Search for a command to run...

Co-Founder, @CreoWis | Teacher, @tapaScript | Founder, @ReactPlay | YouTuber | Writer | Human
Really beautiful and amazing explanation Tapas Adhikary sir I recently got to know about U when I read ur blog on Promise and it was truly amazing loved ur explanation and it clear very much confusion of mine
Hello, I'm learning Javascript from internet and searching answers for knowing how 'this' works in arrow and normal functions get your amazing posts. It all was fine until I get the following part : "What do you think, this would be bound to here inside forEach? It is not an arrow function. It is a regular function, and it has its own execution context. In that execution context, there is nothing called a name. Hence this.name is undefined." Because of in your previous post about binding, the object on which the function is called define the binding of 'this'. So I don't understand which is the Object on which the anonymous function (inside of forEach) is called in this case. It would be good identify that in order to follow the thread of the previous explanations. I am aware of this is 4 year old, and maybe you are in other business, but I get here today and write this question just in any case. Thanks.
Well, I was doing more things to get clarify the 'this' unclear, in the example code from your post:
////////////////////////////////////////////////////
var testHobbies = {
hobbies: ['Cricket', 'Football', 'Blogging'],
name: 'Alex',
logHobbies() {
this.hobbies.forEach(function(elem){
console.log(${this.name} knows ${elem});
});
}
}
////////////////////////////////////////////////////////
So, changing in the code 'this.name' by only 'this' when it runs result the following output;
[object global] knows Cricket [object global] knows Football [object global] knows Blogging
Then taking from your explanation on the Binging part: "if the this keyword is not resolved with any of the above bindings, implicit, explicit or new then, the this binds to the window(global) object."
So in the example code above, the 'this' inside the anonymous function binds to object global, because 'this' keyword is not resolved with any of bindings: implicit, explict or new, and also it doesn't exist in its function context. That is what I understand until here.
In your code snippet under 'apply() method', shouldn't hobby1 and hobby2 be replaced by hobbies[0] and hobbies[1] respectively?
Thanks for reading and commenting.
shouldn't hobby1 and hobby2 be replaced by hobbies[0] and hobbies[1] respectively?
No, actually. The apply method is one step better than the call where you can pass the entire array as an argument. The number of parameters passed to the applied function would be mapped to the number of array elements passed to apply in the same order.

Another way to visualize it, think about the arguments itself. It is available to the function as local variable. See how I can retrieve with the element by element in this case.
var getName = function() {
console.log(this.name + ' likes ' + arguments[0] + ' , ' + arguments[1]);
}
var user = {
name: 'Tapas',
address: 'Bangalore'
};
var hobbies = ['Swimming', 'Blogging'];
getName.apply(user, hobbies);
Hope I was able to clarify. Please let me know.
Tapas Adhikary It is clear to me now. My bad, I mistook the argument-list as parameters.
Thanks John Philip!
In this series, I'll bring some fundamental concepts from JavaScript to you. It is going to be fun learning for JS Beginners(and for Experienced folks too) to get the foundation right.
Introduction Welcome to another post of the series, JavaScript: Cracking the Nuts. This series is all about visiting JavaScript fundamental concepts with more significant details. In this article, I am going to explain another important concept calle...
Traditional SSR is great, but it has a massive buffering problem. Let's look into the SSR Streaming and learn how it could be a game changer.

Learn how to build maintainable, reusable forms in React using design patterns like custom hooks, compound components, and context for scalable CRUD

Learn how JavaScript variables work, including let vs const, primitive and reference types, pass by value, and how JavaScript stores data in memory.

A beginner-friendly introduction to JavaScript covering what it is, how it works, and how to set up your JavaScript environment

Learn how the promises are handled internally using event loop. This concept is essentials to debug and work with async programming.

GreenRoots Blog - A Blog by Tapas Adhikary
186 posts
Educator | YouTuber | Building ReactPlay | Let's Connect
Let me start this article by thanking the readers of my series, JavaScript: Cracking the Nuts for liking and loving it so far. This article will go through another fundamental but equally misunderstood aspect of JavaScript called the this keyword.
It is not mandatory, but if you are new to the series, I would recommend you to go through the previous articles for other fundamental concepts like,
Alright, so let us get started. At the end of the article, you should have a better understanding with,
Many Thanks to the resource links mentioned in the Credits and Resources section. It helped me to master this concept well.
Unlike other articles from the series, this one is going to be a bit lengthy. After going over several tutorials, I felt that one should connect various aspects to understand the concept of this well. For example, the concept of call => apply => bind is very related to understanding this keyword. We need to discuss them together.
I could have broken things into multiple articles but, it is better to be together as the concepts are very inter-related. Hence the lengthy read alert!
Take your favorite beverages, relax, and start reading. I am sure you are going to enjoy it.
this?this is a keyword in JavaScript, and the existence of it is to allow us in,
this is related to.Remember that, when an Execution Context is created in JavaScript, it creates a special thing called, this.
window object.binding.It can be challenging to understand a function's this keyword as it behaves differently in JavaScript than in other languages. When it comes to finding the context of this, we need to see where the function is invoked.
The usage of this can be categorized into four different binding aspects.
Implicit binding is the most used use-case for the this keyword. When we invoke a method of an object, we use the dot(.) notation to access it. In the case of implicit binding, the context of this is bound to the object on which we invoke the method.
Here is an example,
Example:
const user = {
name: 'GreenRoots',
address: 'HashNode',
greeting: function() {
return `Hello, ${this.name} belongs to ${this.address}`
}
};
user.greeting();
Explanation:
In the above example, we invoke the greeting() method on the user object using the dot(.) notation. Hence this is bound to the user object. So, this.name is going to log GreenRoots and this.address is HashNode.
Let's take another example to explain this concept better way,
Example:
function greeting(obj) {
obj.logMessage = function() {
console.log(`${this.name} is ${this.age} years old!`);
}
};
const tom = {
name: 'Tom',
age: 7
};
const jerry = {
name: 'jerry',
age: 3
};
greeting(tom);
greeting(jerry);
tom.logMessage ();
jerry.logMessage ();
Explanation:
In the above example, we have two objects, tom and jerry. We have decorated(enhanced) these objects by attaching a method called logMessage ().
Just notice when we invoke tom.logMessage(), the method is invoked on the tom object. Hence this bound to the tom object. The same applies when jerry.logMessage () is invoked.
We are aware that JavaScript creates an environment to execute the code we write. This environment includes stuff beyond the actual code we write.
It takes care of the memory creation for variables, functions, objects, etc., in the creation phase. Finally, execute the code in the execution phase. This special environment is called JavaScript Execution Context.
There are many such environments(Execution Contexts) in a JavaScript application. Each Execution Context is independent of the other. But we may want to access something from one execution context to another. That is where explicit binding comes into play. We can bind stuff from one context into the context of a different environment for execution using this.
There are three extraordinary methods, call(), apply(), and bind(), help in achieving explicit binding.
With the call() method, the context with which the function has to be called will be passed as a parameter to the call(). Let us see with an example,
Example:
greeting: function() {
return `Hello, ${this.name} belongs to ${this.address}`
}
const user = {
name: 'GreenRoots',
address: 'HashNode'
};
greeting.call(user);
Explanation:
What we see here is, the call() method is invoked on a function called greeting(). The greeting() function just logs a message using this.name and this.address. But what is this here? That gets determined by what has been passed to the call() method.
Here this will bind to the user object because we have passed the user as a parameter to the call() method. Hence this.name should log the value of the user object's name property, i.e., GreenRoots, and similarly, this.address as Hashnode.
In the above example, we have passed just one argument to call(). But, we can pass multiple arguments to call(), if required. Let's take another example to understand that,
Example
var getName = function(hobby1, hobby2) {
console.log(this.name + ' likes ' + hobby1 + ' , ' + hobby2);
}
var user = {
name: 'Tapas',
address: 'Bangalore'
};
var hobbies = ['Swimming', 'Blogging'];
getName.call(user, hobbies[0], hobbies[1]);
Explanation: Notice that we have passed two more arguments here in the call() method. The first argument must be the object context with which the function has to be invoked. Other parameters could be just values to use. Here I am passing Swimming and Blogging as two parameters to the getName() function.
Do you notice a pain point here? In case of a call(), the arguments need to be passed one by one, which is not such a smart way of doing things! That's where our next method apply() comes into the picture.
The hectic way of passing the arguments to the call() method can be solved by another alternate method called apply(). It is the same as call() but allows passing the arguments more conveniently. Have a look,
Example
var getName = function(hobby1, hobby2) {
console.log(this.name + ' likes ' + hobby1 + ' , ' + hobby2);
}
var user = {
name: 'Tapas',
address: 'Bangalore'
};
var hobbies = ['Swimming', 'Blogging'];
getName.apply(user, hobbies);
Explanation: As you see here, we can pass an array as arguments, which is much more convenient than passing one by one.
When you have only one value argument or no value arguments to pass, use call(). When you have multiple value arguments to pass, use apply().
The call() method invokes the function by passing the context of this. The bind() method is similar to the call() but, instead of calling the function directly, bind() returns a brand new function, and we can invoke that instead.
Example:
var getName = function(hobby1, hobby2) {
console.log(this.name + ' likes ' + hobby1 + ' , ' + hobby2);
}
var user = {
name: 'Tapas',
address: 'Bangalore'
};
var hobbies = ['Swimming', 'Blogging'];
var newFn = getName.bind(user, hobbies[0], hobbies[1]);
newFn();
Explanation:
As we see above, the getName.bind() doesn't invoke the function getName(). It returns a new function, newFn and we can invoke is as, newFn().
A Constructor function is created with the new keyword. Here is an example of a Constructor function,
var Cartoon = function(name, animal) {
this.name = name;
this.animal = animal;
this.log = function() {
console.log(this.name + ' is a ' + this.animal);
}
};
We can create the objects using the new keyword as,
var tom = new Cartoon('Tom', 'Cat');
var jerry = new Cartoon('Jerry', 'Mouse');
Let's break it down. Take this line,
var tom = new Cartoon('Tom', 'Cat');
Here the function Cartoon is invoked with the new keyword. Hence this will be bound to the new object created here, tom.
What will be the output of this code execution? What is this bind to here?
var sayName = function(name) {
// 'use strict';
console.log(this.name);
};
window.name = 'Tapas';
sayName();
if the this keyword is not resolved with any of the above bindings, implicit, explicit or new then, the this binds to the window(global) object.
ES6 introduced arrow functions, which don't provide their own this binding. As we have seen so far, in regular functions, the this keyword represented the object that is called the function, which could be the window, the document, user-defined, or whatever.
Arrow functions don't bind their own scope but inherit it from the parent.
Example time. Let us see it working.
var testHobbies = {
hobbies: ['Cricket', 'Football', 'Blogging'],
name: 'Alex',
logHobbies() {
this.hobbies.forEach((elem) => {
console.log(`${this.name} knows ${elem}`);
});
}
}
Here the logHobbies() method iterates through the hobbies and logs them into the console. Notice, we are using an arrow function in forEach. The this inside the arrow function would bind to the object testHobbies as there is no this binding for the arrow functions, and it always binds to the parent one.
Hence invoking testHobbies.logHobbies() would correctly log as,
Alex knows Cricket
Alex knows Football
Alex knows Blogging
Now let us bring a twist to it. Notice the modification I have made below. Instead of an arrow function, the for-each uses a regular function.
var testHobbies = {
hobbies: ['Cricket', 'Football', 'Blogging'],
name: 'Alex',
logHobbies() {
this.hobbies.forEach(function(elem){
console.log(`${this.name} knows ${elem}`);
});
}
}
What do you think, this would be bound to here inside forEach? It is not an arrow function. It is a regular function, and it has its own execution context. In that execution context, there is nothing called a name. Hence this.name is undefined.
Hence the output will be,
undefined knows Cricket
undefined knows Football
undefined know Blogging
We will see it in more detail in future articles on Scope and Closure.
Normally, in global scope this keyword refers to window object,
<script>
console.log(this); //returns window object.
</script>
In JavaScript strict mode also, the this keyword in global scope returns window object. However, it behaves differently in the function scope.
See the following example,
<script>
"use strict;"
console.log(this);
function testThis() {
"use strict";
console.log('testThis', this);
}
testThis();
</script>
It will log the following output in the console,
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
testThis undefined
Yes, Understanding this is easy! But at the same time, it could be challenging to comprehend the rules and usage of this. We will understand this better when we focus on the question, Where is the function invoked?
In most of the cases, the usage would be with Implicit Binding. There will be used with explicit binding with the call(), apply(), and bind(). With many of the JavaScript-based frameworks like Reactjs, Angular, etc., we use arrow functions.
Just note, as long as you have these rules understood and practiced, I am sure you will agree that this is really easy to work with!
this.thisI hope you find the article useful. Please Like/Share so that it reaches others as well. If you enjoyed this article or found it helpful, let's connect. You can find me on Twitter(@tapasadhikary) sharing thoughts, tips, and code practices.
To get e-mail notifications on my latest posts, please subscribe to my blog by hitting the Subscribe button at the top of the page.
I'll explain other fundamental concepts called Scope and Closure in the series's future posts. Stay Tuned.