Back to Overview

Functional Programming

programming fundamentals paradigm software-design

What is Functional Programming?

Functional Programming is like writing recipes for a kitchen where there’s one important rule: never change the original ingredients!


Instead of modifying things that already exist, you always create new things. It’s like if you want a sandwich with extra cheese - instead of adding cheese to an existing sandwich, you make a whole new sandwich with cheese already in it.

Simple Analogy

Think of Functional Programming like a special kitchen with one rule:


  • Regular Programming: Like a kitchen where everyone shares ingredients and changes them. If someone starts making a sandwich, another person might add more cheese, and a third person might add lettuce. Pretty soon, no one knows exactly what’s in the sandwich!

  • Functional Programming: Like a kitchen where everyone follows one rule: “Never change someone else’s food!”
    • If you want to add cheese to a sandwich, you make a completely new sandwich with cheese in it
    • The original sandwich stays exactly the same
    • Each recipe always makes the same food when you use the same ingredients

Key Concepts

  • Pure Functions: Like recipes that always make the same food when you use the same ingredients
  • Immutability: Once you make something, you never change it - you always make something new instead
  • First-Class Functions: Being able to use recipes as ingredients in other recipes
  • Function Composition: Combining simple recipes to make more complicated ones

Example

// Regular way (changing things)
function addCheeseToSandwich(sandwich) {
  sandwich.cheese = true;  // Changes the original sandwich
  return sandwich;
}

let mySandwich = { bread: true, lettuce: true };
addCheeseToSandwich(mySandwich);
// Now mySandwich has cheese added to it


// Functional way (making new things)
function makeSandwichWithCheese(sandwich) {
  return {
    ...sandwich,  // Copy everything from the original sandwich
    cheese: true  // Add cheese to the new sandwich
  };
}

let originalSandwich = { bread: true, lettuce: true };
let newSandwich = makeSandwichWithCheese(originalSandwich);
// originalSandwich stays the same
// newSandwich is a new sandwich with cheese