Course contentsShow
← JavaScript
Lesson 1744 of 2,72337. Functional Programming PatternsFree lesson

Pure vs Impure: Comparison Examples

Compare pure and impure versions of the same function to see the difference.

Pure vs Impure: Comparison Examples

You'll learn: How to distinguish pure from impure functions by comparing concrete before-and-after examples.

The Core Idea

The best way to internalize purity is to see the same logic written two ways: once with side effects or non-determinism (impure), and once without (pure). This side-by-side comparison makes the principles tangible.

Example 1: Array Mutation

Impure (mutates external state):

let items = [1, 2, 3];

function addItem(item) {
  items.push(item);  // modifies external array
  return items;
}

addItem(4);  // items is now [1, 2, 3, 4]

Pure (no mutation):

function addItem(arr, item) {
  return [...arr, item];  // returns new array
}

const items = [1, 2, 3];
const newItems = addItem(items, 4);  // items unchanged, newItems is [1, 2, 3, 4]

Example 2: Non-Determinism

Impure (output varies):

function getTimestamp() {
  return Date.now();  // different every call
}

Pure (deterministic):

function formatTimestamp(timestamp) {
  return new Date(timestamp).toISOString();  // same input → same output
}

Example 3: Console Logging

Impure (side effect):

function calculate(a, b) {
  console.log('Calculating...');  // I/O side effect
  return a + b;
}

Pure (no side effects):

function calculate(a, b) {
  return a + b;  // just returns value
}

Key Takeaway: Pure functions take all inputs as arguments, return new values without mutation, and avoid side effects like I/O or randomness—making them predictable, testable, and easier to reason about.