jsComplete
jsDrops is a jsComplete series of short educational emails on full-stack JavaScript and related topics. You can see a sample email below.

Having troubles? Email us at [email protected]


Hello,

While working on my upcoming redo of the Reactjs Getting Started course, I needed to come up with a short and concise way to describe the value of using arrow functions over regular functions in JavaScript.

This is what I came up with:

Arrow functions give access to their defining environment while regular functions give access to their calling environment.
  • The value of the this keyword inside a regular function depends on HOW the function was CALLED.

  • The value of the this keyword inside an arrow function depends on WHERE the function was DEFINED.

If you’ve understood arrow functions before, do you think that the above is a good way of putting it?

Here is a code example to expand on the explanation. Try to figure out what will be printed in Output #1 through #4:

// jsdrops.com/arrow-functions

this.whoIsThis = 'TOP'; // Identify this scope

// Defining
const fancyObj {
  whoIsThis: 'FANCY', // Identify this object

  regularF: function () {
    console.log('regularF', this.whoIsThis);
  },

  arrowF: () => {
    console.log('arrowF', this.whoIsThis);
  },
};

// Calling
console.log('TOP-LEVEL', this.whoIsThis); // It's "TOP" here

fancyObj.regularF(); // Output #1
fancyObj.arrowF();   // Output #2

fancyObj.regularF.call({whoIsThis: 'FAKE'}); // Output #3
fancyObj.arrowF.call({whoIsThis: 'FAKE'});   // Output #4

You have a regular function and an arrow function defined and called in the same environment.

The regular function will always use its this to represent who called it. In the example above, the caller of both functions was the fancyObj itself. That’s why Output #1 will be "FANCY"

The arrow function will always print the this scope that was available at the time it was defined. That’s why Output #2 will be "TOP".

This holds true even if the caller was changed using .call, .apply, or .bind. These functions are used to change the calling environment. The first argument to them becomes the new "caller" of the function. That’s why Output #3 will be "FAKE", but guess what Output #4 is going to be? The arrow function does not care about this caller change. It’ll still output "TOP".

You can run the code example above at jsdrops.com/arrow-functions.

Best,
Samer

Get jsDrops