Take 'this' Quiz, Understand How 'this' Works in JavaScript
Tags: challenge, javascript, beginners
Published: 2020-02-09 21:28:29

Among all the abstract ideas JavaScript has to offer, the <b>'this'</b> keyword can be one of the most challenging concepts to grasp. On the surface, <b>'this'</b> seems like an intuitive keyword that simply refers to the environment (or context) it resides in. 

As you look deeper into the JavaScript runtime, i.e. where the code is being executed, <b>'this'</b> keyword might end up grabbing things you did not expect.

In this post, I created 4 simple scenarios where <b>'this'</b> keyword can be interpreted differently, each followed by a multiple-choice section, a long pause (in case you scrolled too fast and accidentally saw the answer), and the answer with explanations.

Feel free to play around with the code on your console or text editor. Remember, the more and varied situations you encounter, the better you'll be at identifying and understanding <b>'this'</b> keywords.

Ready? Let's do <b>this</b>!

<h3>Challenge #1</h3>

```javascript
const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();
```

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.
(C) Hey, caller just called.


...


...


...


...


...


...


...


...


...


...

The answer is... 



<i><b>(B) Hey, mom just called.</b></i>

Here's the code block again:
```javascript
const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();
```

Here we have a function declaration inside the call object. As a general rule, <b>'this'</b> is determined by the object invoking a function. Therefore, when the call object invokes says function (call.says()), the <b>'this'</b> keyword inside the says function refers to the call object, making this.caller equal to "mom".

Pretty straight forward, right?


<h3>Challenge #2</h3>
```javascript
const call = {
  caller: "mom", 
  says: () => {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();
```

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.
(C) Hey, caller just called.


...


...


...


...


...


...


...


...


...


...

The answer is... 



<i><b>(A) Hey, undefined just called.</b></i>

Here's the code block again:
```javascript
const call = {
  caller: "mom", 
  says: () => {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

call.says();
```

Wait, isn't this code the same as the first one?

If you look closely, the function declaration from Challenge#1 is now replaced by an arrow function.

Arrow functions, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" target=_blank> as part of ES6 syntax</a>, do NOT have their own <b>'this'</b> keyword. Instead, they will use the <b>'this'</b> keyword of whatever <b>'this'</b> was outside the function when it was created.

In other words, <b>'this'</b> inside the arrow function is not bound to our call object, but instead is already bound to where the call object is being created originally, which in this case is the global object. ~~And because the global object does not know anything about say() function, <b>'this'</b> is undefined.~~ And because the global object does not have a caller property, this.caller is undefined. <i>(shout out to <a href="https://dev.to/nylen">James Nylen</a> for the correction!)</i>


<h3>Challenge #3</h3>
```javascript
const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.says;

newCall();
```

What will the code above log to the console?

(A) Hey, undefined just called.
(B) Hey, mom just called.


...


...


...


...


...


...


...


...


...


...

The answer is... 



<i><b>(A) Hey, undefined just called.</b>

What happened? Let's look at the code again:
```javascript
const call = {
  caller: "mom", 
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.says;

newCall();
```

Here, we declare a new variable, `newCall`, and assign the says function inside the call object to `newCall`. And then we invoke `newCall`, which is a now simple function call.

Notice where we invoke the function. Is it inside the call object? No. We are invoking newCall() function <b>globally</b>, which in turn makes the <b>'this'</b> keyword equal to the global object.

As demonstrated in Challenge#2, since the global object does not have a caller property, you get "undefined" as a result.


By now, you might notice a key pattern: 
<b>Regular functions change their behaviors BASED ON the object that is CALLING the function.</b>


<h3>Challenge #4</h3>
```javascript
function anotherCaller() {
  console.log(`${this.caller} called, too!`);
}

const call = {
  caller: "mom", 
  anotherCaller: anotherCaller,
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.anotherCaller;

newCall();
```

What will the code above log in the console?

(A) mom called, too!
(B) Hey, mom just called.
(C) undefined called, too!

...


...


...


...


...


...


...


...


...


...

The answer is... 



<i><b>(C) undefined called, too!</b>

Again, pay attention to where the function is being invoked:
```javascript
function anotherCaller() {
  console.log(`${this.caller} called, too!`);
}

const call = {
  caller: "mom", 
  anotherCaller: anotherCaller,
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};

let newCall = call.anotherCaller;

newCall();
```

We are invoking newCall() function globally, which means the <b>'this'</b> keyword is referring to the global object. It doesn't matter that we are assigning newCall to a function inside the call object. We are calling newCall globally, and globally is where <b>'this'</b> is assigned.

If you're feeling adventurous, try moving anotherCaller() function inside of the call object, like so:
```javascript
const call = {
  caller: "mom", 
  anotherCaller: function() {
        console.log(`${this.caller} called, too!`)
      },
  says: function() {
    console.log(`Hey, ${this.caller} just called.`);
  }
};


let newCall = call.anotherCaller;
newCall();
```

Based on what we just discussed, what do you think the output will be? 

Try running the code mentally before checking the answer in your browser. If you got it, you got <b>this</b> (the basics, at least)!


<hr>


I hope these examples give you a better picture of how <b>'this'</b> keyword works. If you still find it confusing, worry not. As with everything in programming, practice is key. 

For more examples, check out <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" target=_blank>the official MDN documentation on 'this'</a>. I also highly recommend <a href="https://itnext.io/the-this-keyword-in-javascript-demystified-c389c92de26d" target=_blank>this awesome article</a>. The author provided clear explanations and actually gave me additional insight into some tricky parts in my last challenge.