01 / 20
=> this

Arrow Functions &
Lexical this

Master modern JavaScript's concise function syntax and understand how arrow functions inherit this from their surrounding scope.

JavaScript Programming

What is a Function?

A function is a reusable block of code that performs a specific task. In JavaScript, functions are first-class citizens: they can be stored in variables, passed as arguments, and returned from other functions.

JS
// Traditional function declaration
function greet(name) {
  return "Hello, " + name;
}

// Function expression (stored in a variable)
const greetAsExpression = function(name) {
  return "Hello, " + name;
};

Enter the Arrow Function

Arrow functions use the => syntax to create shorter, more concise functions. They were introduced in ES6 (2015) and are now the most common way to write functions in modern JavaScript.

JS
// Traditional
const add = function(a, b) {
  return a + b;
};

// Arrow function
const add = (a, b) => a + b;

Arrow Syntax Variations

No params
() => value
Use empty parentheses
One param
x => x * 2
Parentheses optional
Multi params
(a, b) => a + b
Parentheses required
JS
// Multi-line body: use braces + return
const calculate = (x, y) => {
  const sum = x + y;
  return sum * 2;
};

What is this?

In JavaScript, this is a special keyword that refers to the context in which a function is called. It changes depending on how the function is invoked, not where it is written.

Global Scope this = window Object: user name: "Alice" Method: sayHi() this = user this.name === "Alice"

The this Problem

With regular functions, this is determined by how the function is called, not where it's defined. This creates a classic bug when using callbacks inside objects:

JS
const timer = {
  seconds: 0,
  start: function() {
    setInterval(function() {
      this.seconds++;       // Bug! "this" is window, not timer
      console.log(this.seconds); // NaN
    }, 1000);
  }
};

Lexical this: The Core Rule

Object method scope this = timer object Regular function() this = window ✕ Own this (runtime) Determined by caller Arrow () => {} this = timer object ✓ Inherited this (lexical) From enclosing scope vs Dynamic binding Lexical binding

The Fix with Arrow Functions

Replace the regular callback with an arrow function, and this automatically refers to the enclosing object:

JS
const timer = {
  seconds: 0,
  start: function() {
    setInterval(() => {
      this.seconds++;       // ✓ "this" is timer
      console.log(this.seconds); // 1, 2, 3...
    }, 1000);
  }
};

Regular vs Arrow: Key Differences

Regular Function Arrow Function
Syntax function(x) { ... } (x) => { ... }
this binding Dynamic (caller) Lexical (definition)
arguments Has its own Inherits from parent
As constructor ✓ Can use new ✕ Cannot use new
Hoisting Declarations hoisted Not hoisted
Best for Methods, constructors Callbacks, inline logic

How to Choose the Right Function

1
Is it a method on an object? Use a regular function so this correctly refers to the object.
2
Is it a callback inside a method? Use an arrow function to inherit this from the method.
3
Is it a standalone utility? Use an arrow function for conciseness (e.g., array .map(), .filter()).
4
Do you need arguments or new? Use a regular function: arrow functions lack both.
5
When in doubt: default to arrow functions for callbacks and short expressions, regular functions for methods.

Example: Arrow Functions with Arrays

Arrow functions shine with array methods like .map(), .filter(), and .reduce():

JS
const numbers = [1, 2, 3, 4, 5];

// Double each number
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// Keep only even numbers
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]

// Sum all numbers
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15

Example: Lexical this in Practice

JS
const team = {
  name: "JavaScript Squad",
  members: ["Alice", "Bob", "Charlie"],

  introduce: function() {
    return this.members.map(member => {
      return `${member} is on ${this.name}`;
    });
  }
};

team.introduce();
// ["Alice is on JavaScript Squad",
//  "Bob is on JavaScript Squad",
//  "Charlie is on JavaScript Squad"]

Example: Event Handlers

A common real-world pattern: using arrow functions inside class methods for event handlers.

JS
class Counter {
  constructor() {
    this.count = 0;
    this.btn = document.querySelector("#btn");

    // ✓ Arrow preserves "this" as the Counter instance
    this.btn.addEventListener("click", () => {
      this.count++;
      console.log(this.count); // 1, 2, 3...
    });
  }
}

Common Mistakes to Avoid

✕ Arrow as Object Method
Using an arrow function as an object method causes this to be the global scope, not the object.
✕ Forgetting Return with Braces
Adding {} but omitting return silently returns undefined.
✕ Returning Object Literals
Writing () => {key: val} is parsed as a block, not an object. Wrap in parentheses: () => ({key: val})
JS
// ✕ Wrong: arrow function as method
const obj = {
  name: "Oops",
  greet: () => console.log(this.name) // undefined!
};

// ✓ Correct: regular function as method
const obj = {
  name: "Works",
  greet() { console.log(this.name); } // "Works"
};

When to Use Which

Scenario Use Arrow Use Regular
Array callbacks ✓ .map(x => x*2)
Event handlers (in class) ✓ preserves this
Promises / async ✓ .then(r => r.json())
Object methods ✓ needs own this
Constructors ✓ arrows can't be new
Prototype methods ✓ needs dynamic this

Question 1 of 5

What does "lexical this" mean in the context of arrow functions?

Question 2 of 5

What will dog.bark() output?

Question 3 of 5

Which of the following is a valid arrow function that returns an object literal?

Question 4 of 5

Which scenario is best suited for an arrow function?

Question 5 of 5

What is the output of app.double()?