Functions

Overview

A function is a reusable block of code designed to perform a specific task. Functions allow programmers to break complex problems into smaller, manageable pieces, reducing redundancy and improving maintainability.

Core Concepts

  • Declaration vs. Expression:
    • Declaration: A named function defined in the global or local scope.
    • Expression: A function assigned to a variable (often anonymous).
  • Parameters & Arguments:
    • Parameters: The placeholders defined in the function signature.
    • Arguments: The actual values passed to the function when it is called.
  • Return Values: The output a function sends back to the caller. If no return is specified, functions often return undefined or void.
  • Higher-Order Functions: Functions that take other functions as arguments or return a function (e.g., map, filter, reduce).
  • Pure Functions: Functions that always produce the same output for the same input and have no side effects (do not modify external state).

Code Examples

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

// Arrow function (Expression)
const add = (a: number, b: number): number => a + b;

// Higher-Order Function example
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // 'map' is the higher-order function

Use Cases

  • Abstraction: Hiding complex logic behind a simple function name.
  • Code Reuse: Writing a validation logic once and using it across the entire app.
  • Event Handling: Passing a function to be executed when a user clicks a button.

Gotchas

  • Side Effects: Functions that modify global variables or perform I/O can make code unpredictable and hard to test.
  • Stack Overflow: Deeply nested function calls (especially in recursion) can exceed the memory limit of the call stack.
  • The ‘this’ Context: In some languages (like JS), the value of this inside a function depends on how the function was called, which can lead to confusing bugs.

Related Notes