JavaScript - Arrow Functions

Overview

Estimated time: 25–35 minutes

Arrow functions provide concise syntax and lexical this. They are great for callbacks and small functions.

Learning Objectives

  • Write arrow functions with explicit and implicit returns.
  • Understand lexical this and no arguments binding.

Prerequisites

Examples

const add = (a, b) => a + b;            // implicit return
const toObj = (x) => ({ value: x });     // wrap object literal in parens

// Lexical this
function Timer(){
  this.count = 0;
  setInterval(() => { this.count++; }, 1000); // 'this' refers to Timer
}

Common Pitfalls

  • Arrow functions cannot be used as constructors (new).
  • No own arguments; use rest parameters instead.