Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Using Arrow Functions
3.
Arrow Functions as Methods
4.
Explicit, Hard, and New binding
4.1.
Explicity Binding
4.2.
Hard Binding
4.3.
New Binding
5.
API Calls
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Explain "this" keyword and Scope of this in Javascript Arrow Functions

Author Abhay Trivedi
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

The arrow function, which employs a fat arrow (=>), was introduced in ES6 as a new way of defining JavaScript functions. Using the arrow function, curly braces, parenthesis, function, and return keywords become optional. One of the main differences between arrows and regular functions is that arrow functions can only be anonymous. They are not bound to any identifier. Arrow functions do not bind their own; instead, they inherit the one from the parent scope, called "lexical scoping". It makes arrow functions an excellent choice in some scenarios but a terrible one in others. Thus they are created dynamically. We cannot name an arrow function as we do for the regular functions. However, if you'd like to call or reuse an arrow function, you must assign it to a variable.

This article will discuss using the arrow function to write your JavaScript functions. Focusing on converting regular functions to arrow functions as we consider when not to use arrow functions. It is essential to understand the arrow functions to have prior knowledge of JavaScript functions.

Using Arrow Functions

Take a look at the example of using the arrow function with this:

// function definition
const myFunction = () => {
  console.log(this);
};

myFunction();

 

Output:

What can we expect this to be? Precisely, as with normal functions, windows, or global objects. The consequence is the same, but the cause isn't the same. By default, the scoped of regular functions is linked to the global one; however, arrows functions, as previously said, do not have their own "this" keyword and instead inherit it from the parent scope, in this case, the global one.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Arrow Functions as Methods

What would happen if we added, "use strict"? It will be the same result since the scope comes from the parent one.

const myObject = {
  myMethod: () => {
    console.log(this);
  }
};

myObject.myMethod();

 

Output:

One might argue that it depends on how the method is called, same as regular functions, but that's not the case here. Remember, arrow functions don't bind their scope but inherit it from the parent one, which in this case is the window or the global object.

const myObject = {
  myArrowFunction: null,
  myMethod: function (){
    this.myArrowFunction = () => {
      console.log(this);
    };
  }
};

myObject.myMethod();

 

Output:

When we call myObject.myMethod(), we tend to initialize myObject.myArrowFunction with an arrow function inside the method myMethod so that it will inherit its scope. We can see a perfect use case, closures.

You can practice by yourself with the help of Online Javascript Compiler for better understanding.

Explicit, Hard, and New binding

What would happen when we attempt to bind a scope with any of the below techniques?

const myFunction = () => {
  console.log(this);
};
const myObject = {};

Explicity Binding

myFunction.call(myObj, args1, args2, ...) // this => window or global object
myFunction.apply(myObj, [array of args]) // this => window or global object

Hard Binding

const myFunctionBound = myFunction.bind(myObject);
myFunctionBound(); // this => window or global object

New Binding

new myFunction(); // Uncaught TypeError: myFunction is not a constructor

It does not matter how we attempt to bind the scope; it will never work. Also, arrows functions are no constructors, so you can not use new with them.

API Calls

The Arrow functions are a good choice for API calls (asynchronous code ), only if we use CLOSURES.

myObj = {
  myMethod: function () {
    helperObject.doSomethingAsync('CodingNinjas', () => {
      console.log(this); // this => myObj
    });
  },
};

It is the perfect example; we ask to do something async, wait for the answer to do some actions, and don't have to worry about the scope we were working with. Though what would happen if, for any reason, we refactor the code and extract that function out to be reused, for example:

const reusabledCallback = () => {
  console.log(this);  // this => window or global object
};
myObj = {
  myMethod: function () {
    helperObject.doSomethingAsync('CodingNinjas', reusabledCallback);
  },
};

If we do so, we would be violating the current working code, and remember that it doesn't matter how we bind the scope; it won't work. So if you plan to do so, you have to use normal functions and bind the scope manually like

const reusabledCallback = function () {
  console.log(this);  // this => myMethod
};
myObj = {
  myMethod: function () {
    helperObject.doSomethingAsync('CodingNinjas', reusabledCallback.bind(myObject));
  },
};

 

Output:


Check out this problem - Redundant Braces

Frequently Asked Questions

  1. What is “this” keyword in JavaScript?
    The "this" keyword points towards the current object in the method or constructor. The most standard use of the "this" keyword eliminates the confusion between class attributes and parameters with the same name  (since a class attribute is shadowed by a method or constructor parameter).
     
  2. What is an arrow function?
    The arrow function, which employs a fat arrow (=>), was introduced in ES6 as a new way of defining JavaScript functions. Using the arrow function, curly braces, parenthesis, function, and return keywords become optional.
     
  3. Why are arrow functions used?
    Arrow functions plan to fix the problem where we require to access a property of this inside a callback. There are considerable ways to do that: One could assign this to a variable, use bind, or use the third argument available on the Array aggregate methods.
     
  4. What is the advantage of the arrow function in JavaScript?
    This arrow function lowers lots of code and makes the code more readable. The syntax of the arrow function automatically binds "this" keyword to the surrounding code's context. Writing the arrow function (=>) is more flexible as compared with the writing function keyword. 
     
  5. Do arrow functions have a "this" keyword?
    Arrow functions treat “this” keyword differently. They don't define their context since it doesn't have their own "this" context. They inherit that from the parent scope whenever you call the "this" keyword.

Conclusion

This article gives information about the "this" keyword and its scope in javascript arrow functions. Arrow functions are a powerful feature of ES6, but we must use them with care and caution. We continuously find places where arrow functions are not usable, which can cause difficulty tracking errors, especially if you don't understand how they work.

Click here to read about Explain Memoization in JavascriptDebounce and ThrottleImplement Linear Search and Binary Search in an Array.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Previous article
Lexical Scoping
Next article
Explain the difference between shallow Copy and Deep Copy
Live masterclass