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 the function declarations to arrow functions
  2. Use implicit returns where the function body is a single expression
  3. Create a function that uses a callback with arrow functions (no arrays)
πŸ’° 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"