Arrow Functions

Arrow Functions
πŸ‘¨β€πŸ’Ό Arrow functions are a concise syntax for writing functions. They're especially useful for callbacks and short functions.
// Function declaration
function double(n: number): number {
	return n * 2
}

// Arrow function equivalent
const double = (n: number): number => {
	return n * 2
}

// Arrow function with implicit return (no braces!)
const double = (n: number): number => n * 2

When to Use Each Form

ContextUseExample
Top-level named functionsFunction declarationfunction processOrder() { ... }
CallbacksArrow functionapplyToNumber(5, (n) => n + 1)
Short single-expression funcsArrow (implicit)const double = (n) => n * 2
Object methodsMethod shorthand{ calculate() { ... } }
🐨 Open
index.ts
and:
  1. Convert double and greet from function declarations to arrow functions with implicit returns
  2. Convert calculateTotal to an arrow function but keep a block body and explicit return (it has multiple lines)
  3. Create an arrow function isEven(n: number) that returns whether n is even
  4. Create applyToNumber(value: number, transform: (n: number) => number): number that applies transform to value and returns the result
  5. Create arrow functions triple (multiply by 3) and square (multiply a number by itself)
  6. Export: double, greet, calculateTotal, isEven, applyToNumber, triple, square

Required exports

double, greet, calculateTotal, isEven, applyToNumber, triple, square

Completion criteria

  • double, greet, calculateTotal, and isEven are arrow functions
  • double(5) β†’ 10; double(0) β†’ 0; double(-3) β†’ -6
  • greet('Alice') β†’ "Hello, Alice!"; greet('Bob') β†’ "Hello, Bob!"
  • calculateTotal(60, 0.1) β†’ 66; calculateTotal(100, 0.05) β†’ 105
  • isEven(4) / isEven(0) β†’ true; isEven(7) β†’ false
  • applyToNumber(5, triple) β†’ 15; applyToNumber(6, square) β†’ 36
πŸ’° Implicit returns use a single expression and no braces.
πŸ’° Callbacks are often written as arrow functions.
A callback is a function you pass to another function to be called later. In the example above, (n) => n + 1 is a callbackβ€”we're passing it to applyToNumber, which calls it with the value 5. Functions that accept other functions as arguments are called higher-order functions. You'll use this pattern a lot with array methods like map, filter, and reduce.

Please set the playground first

Loading "Arrow Functions"
Loading "Arrow Functions"