Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 60

Arrow Functions and Lexical 'this'

This lesson is built with resources from youtube.com, 33jsconcepts.com and 1 more site.

Hello! In our last lesson, we covered the rest parameter, a modern ES6 feature for creating flexible functions. We saw that it works perfectly with arrow functions, a topic we briefly touched upon. Today, we'll dive deep into that cornerstone of modern JavaScript.

This lesson is all about arrow functions (=>). Your goal is to not only learn their concise syntax but, more importantly, to understand the fundamental difference in how they handle the this keyword compared to regular functions. This concept is one of the most important "under the hood" details you'll learn, and mastering it is essential for writing code in Next.js and React, where arrow functions are used constantly.

Part 1: A Shorter Way to Write Functions

At its core, an arrow function is a more compact way to write a function expression. Let's see how to convert traditional functions into this modern syntax.

JavaScript ES6 Arrow Functions Tutorial

The video 'JavaScript ES6 Arrow Functions Tutorial' from Web Dev Simplified provides a clear, step-by-step guide to the syntax. We'll watch a few short clips to cover the main rules.

Watch from the beginning to 04:24. As you watch, notice: How the function keyword is removed and the => is added. The special rule for functions with only one parameter (parentheses are optional). How to write a function with no parameters. The concept of an implicit return, where you can omit the curly braces {} and the return keyword for single-line functions.

Let's summarize the syntax rules from the video:

  1. Basic Conversion: A function expression like const add = function(a, b) { return a + b; } becomes const add = (a, b) => { return a + b; }. You drop the function keyword and add a "fat arrow" => after the parameters.

  2. Implicit Return: If the function body is just a single return statement, you can make it even shorter. The version above can be written as:

    // The result of a + b is automatically returned.
    const add = (a, b) => a + b;
    
  3. Single Parameter: If there's only one parameter, you can omit the parentheses around it.

    // Regular function
    const square = function(x) { return x * x; };
    
    // Arrow function with implicit return and no parentheses
    const square = x => x * x;
    
  4. No Parameters: If there are no parameters, you must use empty parentheses.

    // Regular function
    const getRandom = function() { return Math.random(); };
    
    // Arrow function
    const getRandom = () => Math.random();
    

This shorter syntax is especially useful for callback functions, which you've seen with array methods.

JavaScript ES6 Arrow Functions Tutorial

Let's continue with the same video to see why this concise syntax is so powerful for anonymous functions used as callbacks.

Watch from 04:24 to 05:28. Notice how much cleaner the code for addEventListener becomes when using an arrow function.

Test your understanding!

Convert the following traditional function expression into a single-line arrow function.

const getGreeting = function(name) {
  return "Hello, " + name + "!";
};
Show answer
const getGreeting = name => `Hello, ${name}!`;

Explanation:

  1. Since it's an arrow function, we remove the function keyword and add => after the parameter.
  2. Because there is only one parameter (name), we can omit the parentheses around it.
  3. Because the function body is a single return statement, we can use an implicit return, removing the {} and the return keyword.
  4. (Bonus!) Using a template literal, which we covered in a previous lesson, makes the string concatenation even cleaner.

Part 2: The Most Important Difference — Lexical this

The concise syntax is nice, but the real power of arrow functions lies in how they handle the this keyword. This is the "deep theory" part that is crucial for understanding why they are so prevalent in modern JavaScript.

  • Regular Functions: Have a dynamic this. The value of this depends on how the function is called. This can be confusing and lead to bugs. For example, this can change if a method is called by an object (myObj.myMethod()) or if it's passed as a callback.
  • Arrow Functions: Have a lexical this. They do not have their own this context. Instead, they inherit this from their parent scope—the code that contains them.

This "automatic" context binding is a huge advantage.

Arrow Function 'this' Context Comparison
This visual illustrates the core idea. With a regular function, you'd often have to save the `this` context to a variable (like `self` or `that`) to use it inside a callback. An arrow function does this for you automatically by inheriting `this` from its surrounding environment.

Let's watch a clear demonstration of this behavior.

JavaScript ES6 Arrow Functions Tutorial

The next clip from the Web Dev Simplified video provides the perfect example using a Person object with a setTimeout callback. It shows the problem with regular functions and how arrow functions solve it.

Watch from 05:28 to 09:00. Pay close attention to why this.name is undefined in the regular function example but works perfectly in the arrow function example.

As the video showed, inside the setTimeout callback:

  • The regular function created its own this context, which was the global window object (or undefined in strict mode), where name does not exist.
  • The arrow function didn't create its own this. It looked up and used the this from its parent, the printNameArrow method, which correctly pointed to the person instance.

This lexical this behavior is why you'll see arrow functions used for almost all callbacks in Next.js and React components. It guarantees that this always refers to the component instance, preventing a common category of bugs.


Part 3: When NOT to Use Arrow Functions

Because arrow functions don't have their own this binding, they are not a complete replacement for regular functions. There are specific situations where you need the dynamic this that regular functions provide.

Modern JavaScript features essential for React: Arrow ...

This article from the 'Modern JavaScript features' series on Medium clearly explains the most common mistake: using an arrow function for an object method.

Read the section titled 'Mistake: Overusing Arrow Functions', focusing on the user object example. It perfectly illustrates why a regular function is needed for an object method that references the object's own properties.

To summarize, here are the main places you should avoid arrow functions:

  1. Object Methods: When you want this to refer to the object itself.

    const user = {
      name: "Alice",
      // INCORRECT: `this` would refer to the global scope, not `user`.
      greet: () => `Hello, ${this.name}`, 
      
      // CORRECT: Use a regular function or method shorthand.
      sayHi() { 
        return `Hi, ${this.name}`;
      }
    };
    
    console.log(user.sayHi()); // "Hi, Alice"
    
  2. Constructor Functions: Arrow functions cannot be used with the new keyword to create instances.

  3. Event Handlers that need this: When adding an event listener, you sometimes want this to refer to the DOM element that triggered the event. An arrow function would prevent this by inheriting this from the outer scope instead.

Test your understanding!

The following code is supposed to log "This car is a Ford". However, it logs "This car is a undefined". Why is it broken, and how would you fix it?

const car = {
  brand: 'Ford',
  describe: () => {
    console.log(`This car is a ${this.brand}`);
  }
};

car.describe();
Show answer

The Problem:
The describe method is an arrow function. Arrow functions do not have their own this binding; they inherit this from the surrounding (global) scope. In the global scope, this.brand is undefined.

The Fix:
You should use a regular function or the shorthand method syntax, which allows this to be dynamically bound to the car object when car.describe() is called.

const car = {
  brand: 'Ford',
  // Fix: Use shorthand method syntax
  describe() {
    console.log(`This car is a ${this.brand}`);
  }
};

car.describe(); // Correctly logs: "This car is a Ford"

Conclusion

You've now learned about one of the most impactful features of modern JavaScript. Understanding not just the "how" but the "why" of arrow functions will make your journey into frameworks like Next.js much smoother.

Key Takeaways:

  • Syntax: Arrow functions (=>) offer a more concise syntax for writing functions, especially for single-line returns and callbacks.
  • Lexical this: This is the most critical concept. Arrow functions inherit this from their parent scope. They do not have their own this context.
  • Dynamic this: Regular functions get a this value that is determined by how they are called.
  • Use Cases: Arrow functions are ideal for callbacks (e.g., in array methods like .map() or in setTimeout) where you want to preserve the this from the outer context.
  • When to Avoid: Do not use arrow functions for object methods or constructor functions where a dynamic this that points to the object instance is required.

Next Up

In our next lesson, we will begin our exploration of asynchronous JavaScript. You'll learn the difference between synchronous and asynchronous code and see how JavaScript handles operations that take time, such as fetching data from a server. You will find that arrow functions are used extensively in modern asynchronous patterns, making today's lesson a vital prerequisite.