Function Expressions and Arrow Functions

1. Welcome and Icebreaker:

  • If you could create a shortcut for any repetitive task in your life, what would it be?

2. Outline the Session:

  • We’ll explore function expressions and arrow functions in TypeScript.
  • Learning Outcomes: Understand the difference between function declarations, expressions, and arrow functions, and when to use each.
  • Let’s get hands-on!

3. Concept Explanation:

  • Function Expression: Assigns a function to a variable. Can be named or anonymous.
    const add = function(a: number, b: number): number {
      return a + b;
    };
    
  • Arrow Function: A shorter syntax for writing functions. Inherits this from the surrounding context (lexical this).
    const add = (a: number, b: number): number => a + b;
    
  • When to Use:
    • Use arrow functions for short, simple functions, especially as callbacks.
    • Use function expressions when you need a function as a value.
    • Arrow functions do not have their own this, arguments, or super.

4. Live Coding Demonstration:

// Function Expression
const multiply = function(x: number, y: number): number {
  return x * y;
};
console.log(multiply(2, 3)); // 6

// Arrow Function (concise)
const divide = (a: number, b: number): number => a / b;
console.log(divide(10, 2)); // 5

// Arrow Function (block body)
const isPositive = (n: number): boolean => {
  return n > 0;
};
console.log(isPositive(-1)); // false

// Arrow function as a callback
const numbers = [1, 2, 3, 4];
const squares = numbers.map(n => n * n);
console.log(squares); // [1, 4, 9, 16]

// Arrow function and lexical this
const person = {
  name: "Alice",
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}`);
    }, 1000);
  }
};
person.greet();

5. Tasks:

  • Short Exercise:
    1. Write a function expression subtract that takes two numbers and returns their difference.
    2. Write an arrow function double that takes a number and returns twice its value.
    3. Use the filter method with an arrow function to create a new array containing only even numbers from [1, 2, 3, 4, 5, 6].