Course contentsShow
← Computer Science
Lesson 2132 of 2,87248. Programming ParadigmsFree lesson

Pure Functions and Immutability

Learn what makes a function pure and why immutability is foundational to functional programming.

Pure Functions and Immutability

You'll learn what makes a function "pure" and why unchanging data is the bedrock of functional programming.

What is a Pure Function?

A pure function is like a mathematical function: given the same input, it always returns the same output, with no side effects. It doesn't modify variables outside its scope, perform I/O, or depend on external state.

Think of it like a vending machine that's perfectly predictable: insert $1.50, get a soda. Every time. No surprises, no changes to the world around it (besides giving you the soda).

Two requirements for purity:

  1. Deterministic: Same inputs → same output, always
  2. No side effects: Doesn't modify external state or interact with the outside world

What is Immutability?

Immutability means data cannot be changed after creation. Instead of modifying existing data, you create new data with the desired changes.

This is like writing in pen instead of pencil. Rather than erasing and rewriting, you start fresh on a new line. Your original note remains unchanged—a complete history of what was.

Why They Matter Together

Pure functions and immutability form a powerful partnership. When functions don't mutate data and always produce the same results, your code becomes:

  • Predictable: No hidden state changes
  • Testable: Easy to verify behavior
  • Parallelizable: Safe to run concurrently without race conditions
  • Debuggable: Easier to reason about cause and effect

Without mutable state to track, you eliminate entire classes of bugs common in imperative programming.

Key Takeaway: Pure functions depend only on their inputs and produce no side effects; immutability ensures data never changes, making programs predictable, testable, and safe for concurrent execution.