All lessons

Functions

9 min · TypeScript

Package code under a name, with typed inputs and outputs.

TypeScript · Functions0/5 cleared

Enemy 1 of 5

This code defines a function called double that takes a number and returns it times two, then calls it with 5 and logs the result. Press Run to see 10.

Why this works

A function names a reusable block of code: write it once, then call it wherever it's needed. Defining a function doesn't run it; it only runs when called by name with parentheses, e.g. double(5).

In TypeScript you can type each parameter and the return value: function double(n: number): number means double takes one argument, n, which must be a number, and promises to return a number back. This is one of the biggest practical wins TypeScript offers: if double("5") is ever called by mistake somewhere in a large codebase, TypeScript flags it immediately rather than letting the mistake ship and fail at runtime, possibly far from where the bug actually originated.

Use return to hand a value back to whoever called the function. If the function's return type is declared as number but a code path inside it tries to return a string instead, TypeScript will refuse to compile until that's fixed.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.