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
| Context | Use | Example |
|---|---|---|
| Top-level named functions | Function declaration | function processOrder() { ... } |
| Callbacks | Arrow function | applyToNumber(5, (n) => n + 1) |
| Short single-expression funcs | Arrow (implicit) | const double = (n) => n * 2 |
| Object methods | Method shorthand | { calculate() { ... } } |
π¨ Open
and:
- Convert
doubleandgreetfrom function declarations to arrow functions with implicit returns - Convert
calculateTotalto an arrow function but keep a block body and explicitreturn(it has multiple lines) - Create an arrow function
isEven(n: number)that returns whethernis even - Create
applyToNumber(value: number, transform: (n: number) => number): numberthat appliestransformtovalueand returns the result - Create arrow functions
triple(multiply by 3) andsquare(multiply a number by itself) - Export:
double,greet,calculateTotal,isEven,applyToNumber,triple,square
Required exports
double, greet, calculateTotal, isEven, applyToNumber, triple,
squareCompletion criteria
double,greet,calculateTotal, andisEvenare arrow functionsdouble(5)β10;double(0)β0;double(-3)β-6greet('Alice')β"Hello, Alice!";greet('Bob')β"Hello, Bob!"calculateTotal(60, 0.1)β66;calculateTotal(100, 0.05)β105isEven(4)/isEven(0)βtrue;isEven(7)βfalseapplyToNumber(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.π Function Forms