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'
};