Arrow Functions & Lexical 'this' in JavaScript

🟢 Beginner Level | JavaScript Core Syntax

📖 Definition

Arrow Functions (introduced in ES6) offer a compact syntax for writing function expressions and inherit lexical this from their surrounding parent scope rather than defining their own dynamic this binding.

🌍 Multilingual Explanations

English

Arrow functions use () => {} syntax with implicit returns for single expressions. They do not have their own this, arguments object, or prototype.

Hindi

Arrow functions const add = (a, b) => a + b; short syntax dete hain. Inka apna this nahi hota, ye parent scope ka this inherit karte hain.

⚖️ Regular Functions vs Arrow Functions Matrix

Feature Regular Function Arrow Function
Syntax function name() {} const name = () => {}
`this` Binding Dynamic (bound at call-time) Lexical (inherited from enclosing scope)
Constructor (`new`) Yes (can be instantiated) No (throws TypeError)
`arguments` Object Available natively Not available (use rest parameters ...args)

💡 Production Code Example

// Implicit return for single-expression arrow functions
const double = n => n * 2;
console.log(double(5)); // Output: 10

// Lexical 'this' inside object method callback
const timer = {
    seconds: 0,
    start() {
        setInterval(() => {
            this.seconds++; // Inherits 'this' from timer object
            console.log("Elapsed:", this.seconds);
        }, 1000);
    }
};

⚠️ Common Pitfalls

Using Arrow Functions as Object Methods: Writing const obj = { name: "Alex", greet: () => console.log(this.name) } results in undefined because this points to global window/module scope.

🎯 Tiered Practice Exercises

  1. Beginner: Convert a regular function calculating array square roots into a concise 1-line arrow function.
  2. Intermediate: Fix an object method callback bug where this.value was undefined using an arrow function.
  3. Advanced: Explain why arrow functions cannot be used as generator functions or constructor functions.

🧭 Navigation

← 01. Function Declarations & Expressions | Functions Hub | 03. Parameters, Default Values & Rest Syntax →