Arrow Functions

📚 Lesson 7 of 22  •  ⏱ 9 min read  •  Beginner

Basic Syntax

JavaScript
// Regular function
function add(a, b) { return a + b; }

// Arrow function — equivalent
const add = (a, b) => { return a + b; };

// Implicit return — no curly braces, expression is returned
const add = (a, b) => a + b;

// One parameter — parentheses optional
const double = n => n * 2;

// No parameters — parentheses required
const greet = () => "Hello!";

With Array Methods — Where Arrows Shine

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

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

// filter — keep matching elements
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]

// reduce — accumulate a value
const total = numbers.reduce((sum, n) => sum + n, 0);
// 15

// Chaining
const result = numbers
  .filter(n => n > 2)
  .map(n => n * 10);
// [30, 40, 50]

Implicit Return with Objects

JavaScript
// Returning an object — wrap in parentheses
const makeUser = (name, age) => ({ name, age });

makeUser("Priya", 25);  // { name: "Priya", age: 25 }

// Without parens, {} is treated as a code block — returns undefined
const broken = (name) => { name };  // returns undefined!

this Binding — Key Difference

JavaScript
const timer = {
  seconds: 0,

  // Regular function — 'this' changes based on call context
  startBad() {
    setInterval(function() {
      this.seconds++;  // 'this' is window, not timer!
    }, 1000);
  },

  // Arrow function — 'this' is inherited from enclosing scope
  startGood() {
    setInterval(() => {
      this.seconds++;  // 'this' is timer ✓
    }, 1000);
  }
};

// Don't use arrow functions for object methods
const obj = {
  name: "test",
  getName: () => this.name  // undefined! Arrow can't bind 'this'
};