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

Hidden Impurity: Date.now and Math.random

Recognize common impure operations that break referential transparency.

Hidden Impurity: Date.now and Math.random

You'll learn to recognize two sneaky functions that make your code impure even when they look innocent.

The Illusion of Purity

Some functions look pure because they don't modify external state or take arguments, but they violate a core principle: deterministic output. A truly pure function returns the same result every time you call it with the same inputs. But what if the function takes no inputs at all?

The Culprits

Date.now() and Math.random() are classic examples of hidden impurity:

// Looks pure, but isn't
function getCurrentTimestamp() {
  return Date.now();
}

getCurrentTimestamp(); // 1704067200000
getCurrentTimestamp(); // 1704067201000 (different!)

Even though you're calling the same function with no arguments, you get different results each time. The function depends on an external, changing state: the system clock or random number generator.

Why This Matters

This breaks referential transparency—the guarantee that you can replace a function call with its return value without changing program behavior. You can't replace Date.now() with 1704067200000 everywhere because the real function keeps changing.

function generateId() {
  return `user_${Math.random()}`;
}

// Can't predict or reproduce output
generateId(); // "user_0.6234"
generateId(); // "user_0.1847" (different!)

The Problem They Cause

These functions make testing harder (you can't predict output), debugging trickier (behavior isn't reproducible), and reasoning about code more complex (you lose mathematical guarantees).

Key Takeaway: Functions that depend on the current time, random values, or any external changing state are impure, even if they don't modify anything—they read from sources that break determinism.