Function Declarations

1. Welcome and Icebreaker:

  • What’s your favorite function (in any language) and why?

2. Outline the Session:

  • We’ll learn how to declare functions in TypeScript, including parameters, return types, and optional/default parameters.
  • Learning Outcomes: Understand function syntax, type annotations, and how to use optional/default values.
  • Ask questions anytime!

3. Concept Explanation:

  • Functions are reusable blocks of code that perform a specific task. In TypeScript, you can specify the types of parameters and the return value.
  • Syntax:
    function functionName(param1: type1, param2: type2): returnType {
      // function body
    }
    
  • Optional Parameters: Add ? after the parameter name. Example: function greet(name?: string)
  • Default Parameters: Assign a default value. Example: function greet(name: string = "Guest")
  • Return Type: Specify after the parameter list. If omitted, TypeScript infers it.

4. Live Coding Demonstration:

function add(a: number, b: number): number {
  return a + b;
}
console.log(add(2, 3)); // 5

function greet(name: string = "Guest"): string {
  return `Hello, ${name}!`;
}
console.log(greet()); // Hello, Guest!
console.log(greet("Alice")); // Hello, Alice!

function logMessage(message: string, userId?: number): void {
  if (userId) {
    console.log(`User ${userId}: ${message}`);
  } else {
    console.log(message);
  }
}
logMessage("Welcome!");
logMessage("Welcome!", 42);

5. Tasks:

  • Short Exercise:
    1. Write a function multiply that takes two numbers and returns their product.
    2. Write a function welcomeUser that takes a name (string, optional) and prints a welcome message. If no name is provided, use “Guest”.
    3. Write a function isEven that takes a number and returns true if it’s even, false otherwise.