Arrow functions
An arrow function is a short way to write a function: parameters, `=>`, then the body.
An arrow function is an expression that creates a function. Read it like this: what comes before => is the parameters, and what comes after is the body.
If the body is a single expression, you need no braces and no return: the value of that expression is the result. If you use braces { }, you write return yourself.
Usually you store it in a const, as in lesson 01.02: const triple = (n) => {. That way the name can't be reassigned by accident.
In TypeScript you annotate the parameters, for example (n: number): number => n * 3. The type checker verifies those types, and they are gone when Node runs the code.
Arrows are also handy as callbacks, for example inside .map(), because they are short.
const double = (n: number) => n * 2;
Reach for it when: you need a small function to store in a `const` or to pass as a callback.
Examples
Common mistake
const triple = (n: number) => {
n * 3;
};
console.log(triple(2));Why: With braces the body is a block, and the function only returns something if you write `return`. Here the multiplication is computed and thrown away.
How to write it: Write return n * 3; inside the braces, or drop the braces: (n: number) => n * 3.
