BeginnerTypeScript · Lesson 3 of 7

Functions

Parameters, return types, optional and default values, arrow functions.

A function groups steps under a name so you can reuse them. In TypeScript you annotate each parameter's type and, ideally, the return type — this documents intent and lets the compiler check every call.

Mark a parameter optional with ?, or give it a default value with =. A function that returns nothing has return type void.

Arrow functions ((a, b) => a + b) are a shorter syntax, commonly used for callbacks passed to other functions such as map and filter.

functions.tsTypeScript
function add(a: number, b: number): number {
  return a + b;
}

function greet(name: string, title?: string): string {
  return title ? "Hello, " + title + " " + name : "Hello, " + name;
}

function percentage(score: number, outOf: number = 100): number {
  return Math.round((score / outOf) * 100);
}

const square = (n: number): number => n * n;

function logResult(label: string, value: number): void {
  console.log(label + ": " + value);
}

logResult("add", add(2, 3));
logResult("percentage", percentage(42, 50));
logResult("square", square(9));
console.log(greet("Amina"), "|", greet("Juma", "Mr."));

Key points

  • Annotate every parameter; annotate return types on exported/public functions.
  • ? makes a parameter optional; = value provides a default.
  • Arrow functions are ideal for short callbacks.

Exercise

Write areaOfRectangle(width, height) and areaOfCircle(radius) functions with proper types. Add an optional units parameter (default "cm") to a describeArea function that returns a string like "Area: 12 cm²".

Show solution

Try the exercise yourself first — then compare your approach with this one.

Each function annotates its parameters and return type. describeArea gives units a default value, so callers can leave it out. toFixed(2) formats the number to two decimal places.

areas.tsTypeScript
function areaOfRectangle(width: number, height: number): number {
  return width * height;
}

function areaOfCircle(radius: number): number {
  return Math.PI * radius * radius;
}

function describeArea(area: number, units: string = "cm"): string {
  return "Area: " + area.toFixed(2) + " " + units + "²";
}

console.log(describeArea(areaOfRectangle(3, 4)));      // Area: 12.00 cm²
console.log(describeArea(areaOfCircle(2), "m"));        // Area: 12.57 m²

Check your understanding

  1. What does ? after a parameter name mean, as in title?: string?

  2. What is the return type of a function that returns nothing?

  3. Which is a valid arrow function that squares a number?

  4. What happens when you call percentage(42) if it is declared as percentage(score: number, outOf: number = 100)?

Ask AI