Understand how 'this' works with JavaScript Arrow Functions

Introduction of Arrow Functions

Arrow functions were introduced with ES6 as a new way of writing JavaScript functions. It was introduced to simplify function scope. I have written a detailed post covering the Arrow function. If you have not checked that post, I highly recommend you go through the post – “Quick Reference of Arrow Function in JavaScript“.

Background of ‘this’

‘this’ keyword works differently in JavaScript compared to other programming languages. If you are coming from some other programming language and trying to learn JavaScript, then it might confuse you and you might see some different behaviors while dealing with ‘this’. That is why it is very important to understand how ‘this’ works with JavaScript.

Normally ‘this’ refers to the current instance of the class in other object-oriented programming language. But in JavaScript world, ‘this’ depends on how a function is called.

Let’s see some examples below to understand clearly –

Example 1

Here is the code for our first example –

const employee = {
  name: "Sudipta Deb",
  emplNum: 100,
  printDetails: function () {
    console.log(this.name + " is having employee number: " + this.emplNum);
  },
};

employee.printDetails();

When I will execute this above code block, we will get the output as –

Sudipta Deb is having employee number: 100

In the above example, I am calling the printDetails() method using the employee object, so the this refers to the person object.

Example 2

Now let’s change the code from Example 1 a little bit. Here is the updated code –

const employee = {
  name: "Sudipta Deb",
  emplNum: 100,
  printDetails: function () {
    console.log(this.name + " is having employee number: " + this.emplNum);
  },
};

const printDetails = employee.printDetails;
printDetails();

Now when I will execute the code, here is the result –

undefined is having employee number: undefined

Strange, correct? Let’s understand the reason. In the above example, I am storing the reference of employee.printDetails to printDetails variable. Now when I am calling the function without an object reference, this refers to the global object i.e. window or undefined(since we are in strict mode).

Example 3

Let’s introduce the Arrow function now in the above code.

const employee = {
  name: "Sudipta Deb",
  emplNum: 100,
  printDetails: () => {
    console.log(this.name + " is having employee number: " + this.emplNum);
  },
};

employee.printDetails();

Now if I execute the same code, the result is –

undefined is having employee number: undefined

But this time even though I am calling the method with an object (same as Example 1), I am still getting undefined. The reason behind this is that in this scenario, this is not bound to anything. When this is used with the arrow function, it just inherits from the parent scope which is window in this case.

To test that if I change the code to (by adding a console.log(this))

const employee = {
  name: "Sudipta Deb",
  emplNum: 100,
  printDetails: () => {
    console.log(this);
    console.log(this.name + " is having employee number: " + this.emplNum);
  },
};

employee.printDetails();

I will see the console.log is printing a window object. So this.name and this.emplNum are basically referring to window.name and window.emplNum which is undefined for sure.

Example 4

In the below code, I will show how the Arrow function will work with event handlers. Here is the code which is doing a very simple thing i.e. when the button is clicked, it is changing the background color to yellow.

<!DOCTYPE html>
<html>
  <head>
    <title>Understand how 'this' works with JavaScript Arrow Functions</title>
  </head>
  <style>
    .myStyle {
      background: yellow;
    }
  </style>
  <body>
    <button id="myButton">Print My Name</button>
  </body>
  <script>
    const myBtn = document.querySelector("#myButton");
    myBtn.addEventListener("click", function () {
      console.log("I am inside event listener");
      console.log(this);
      this.classList.add("myStyle");
    });
  </script>
</html>

Now if I execute the above code, I can see that button’s background color is changed to yellow. In the above example, this refers to the button. Now if I change the same code by introducing the Arrow function like below, I will get a TypeError error. The reason behind – this becomes the browser’s window attribute.

Summary

I hope this post will help you to understand how this works with Arrow function. In the next post, I will be explaining how Call(), Bind(), and Apply() method can be used to make this keyword behavior independent of how the function is called. You can read this post – “Understand Call, Bind and Apply in JavaScript“.

One thought on “How ‘this’ works with JavaScript Arrow Functions”

Leave a Reply

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