Function declarations
A function declaration gives a name to a block of code that you can call as many times as you like, using the function keyword.
A function declaration starts with function, then the name, the parameters in parentheses and the body in braces.
function double(n: number): number {
return n * 2;
}
Read it like this: double is a function that takes n and returns n * 2. Without return, the function returns undefined.
JavaScript hoists declarations: you can call the function before the line where you wrote it. That is why many files put the calls on top and the functions below.
In TypeScript, : number is a type annotation. The type checker verifies it, and it is gone when Node runs the code. The course uses this form from lesson 00.04, with function double(n) {.
Reach for it when: you want a named piece of logic that you will reuse, or that makes your program easier to read.
Examples
Common mistake
function double(n: number): number {
n * 2;
}
console.log(double(4));Why: You compute `n * 2` but never return it. Without `return`, the function would give back `undefined`, and the declared type is number.
How to write it: Write return n * 2;.
