AnyCompiler

Functions

A function's parameters and return value can each be typed. TypeScript checks every call site against these types, so passing the wrong kind of argument is caught immediately, not when the function happens to run.

function greet(name: string): string {
  return `Hello, ${name}!`;
}

console.log(greet("Alice"));
console.log(greet("Bob"));
Output
Hello, Alice!
Hello, Bob!

void, and optional/default parameters

void marks a function that doesn't return a meaningful value. A parameter followed by ? is optional — callers can leave it out — and a parameter can also have a default value, making it optional in a different way: it's filled in automatically when omitted.

function logScore(name: string, score: number = 0): void {
  console.log(`${name}: ${score}`);
}

logScore("Alice", 95);
logScore("Bob");
Output
Alice: 95
Bob: 0

Next: arrow functions — a shorter syntax, with the same typing rules.

Practice exercise

Write a function multiply(a: number, b: number = 2): number that returns a * b, then print multiply(5, 3) and multiply(5).