2 min read

Functional Programming (FP)

Functional Programming is a programming paradigm where programs are constructed by applying and composing functions. It emphasizes immutability, pure functions, and declarative code, avoiding shared state and mutable data.

1. Pure Functions

A pure function is a function where:

  1. The return value depends only on its input arguments.
  2. It has no side effects (doesn't modify external state, log to console, write to files, etc.).
// Impure
let count = 0;
function increment() {
    count++; // Modifies external state
    return count;
}

// Pure
function add(a, b) {
    return a + b; // Depends only on inputs, no side effects
}

2. Immutability

In FP, data is immutable. Instead of changing an object or array, you create a new one with the updated values. This makes code predictable and easier to debug.

// Mutable (Bad in FP)
const arr = [1, 2, 3];
arr.push(4); // Modifies original array

// Immutable (Good in FP)
const newArr = [...arr, 4]; // Creates a new array

3. First-Class and Higher-Order Functions

  • First-Class Functions: Functions are treated as values. They can be assigned to variables, passed as arguments, and returned from other functions.
  • Higher-Order Functions: Functions that take other functions as arguments or return them.
// Higher-Order Function (map)
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // Takes a function as argument

4. Declarative vs. Imperative

  • Imperative: Tells the computer how to do things (step-by-step).
  • Declarative: Tells the computer what you want (logic without control flow).

programming/functions-and-scope programming/common-syntax