Skip to content

This keyword in JavaScript arrow function | Example code

  • by

JavaScript Arrow functions have no this value in their scope, so you can access this value of the object. But Normal functions have this value in their scope.

This keyword in the JavaScript arrow function

A simple example code value of the normal function is global this or window. and it allows to you access the global scope.

<!DOCTYPE html>
<html>
<body>

  <script>
    var greeting = 'Hi';
    const obj = {
      greeting: 'Hey Arrow Function',
      fo() {
        const greeting = 'Hola';
        fo2 =  () => {
          const greeting = 'Hello';
          const arrowFo = () => {
            console.log(this.greeting);
          };
          arrowFo();
        };
        fo2();

      },
    };
    obj.fo();
  </script>

</body>
</html> 

Output:

This keyword in JavaScript arrow function

Source: stackoverflow.com

More example

// Regular function
function regularFunction() {
  console.log(this); // 'this' depends on how the function is called
}

// Arrow function
const arrowFunction = () => {
  console.log(this); // 'this' is inherited from the surrounding scope
};

const obj = {
  prop: 'value',
  regular: regularFunction,
  arrow: arrowFunction,
};

regularFunction(); // 'this' depends on the calling context (window or undefined in strict mode)
obj.regular();     // 'this' refers to the 'obj' object
obj.arrow();       // 'this' refers to the 'obj' object, same as the outer scope

Arrow functions, however, behave differently. They do not have their own this context. Instead, they inherit the this value from the enclosing lexical scope (the scope in which the arrow function is defined). This means that the value of this inside an arrow function is the same as the value of this outside the arrow function.

Comment if you have any doubts or suggestions on this JS this keyword.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading