Functions

Lesson 4: Working with Functions

Functions are central to every TypeScript program. In this lesson, you will learn how to type parameters, return values, optional parameters, default values, and modern arrow functions.

Defining Functions

function greet(name: string): void {
  console.log("Hello, " + name);
}

This function accepts a string and does not return a value, so its return type is void.

Return Types

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

Optional Parameters

function welcome(name: string, title?: string): void {
  if (title) {
    console.log("Welcome, " + title + " " + name);
  } else {
    console.log("Welcome, " + name);
  }
}

Default Parameters

function greetVisitor(name: string = "Guest"): void {
  console.log("Hello, " + name);
}

Arrow Functions

const square = (num: number): number => {
  return num * num;
};

Arrow functions provide a shorter modern syntax and are very common in JavaScript and TypeScript projects.

Tip: Use clear parameter and return types so other developers can understand what your function expects and returns.

Summary

Functions become much safer in TypeScript because parameters and return values can be clearly typed. This makes larger programs easier to maintain and debug.