Pure functions and observable effects
Quick answer
A pure function gives equivalent results for equivalent inputs and causes no externally observable side effects. Purity makes local reasoning and repeatable testing easier.
How it works
Pass time, configuration and other changing dependencies as explicit inputs. Local variables and local mutation are compatible with purity when they do not escape or alter caller-owned data. In JavaScript, objects have identity: two fresh but structurally equal results are not necessarily ===. Referential transparency is a reasoning model, not a guarantee of reference identity.
function total(q,price){return q*price;} console.log(total(3,5),total(3,5));Expected output in Node.js:
15 15The result depends only on supplied numbers.
let rate=2;const cost=n=>n*rate;console.log(cost(4));rate=3;console.log(cost(4));Expected output in Node.js:
812Changing external state changes the result of an otherwise identical call.
Common mistakes
Do not label a function pure simply because it returns a value. Reading changing global state or modifying the input can break purity.
Practice
Refactor a function that reads a mutable tax rate so the rate is an explicit parameter.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pure functions and observable effects — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Does local temporary mutation necessarily make a function impure?
Which dependency makes repeatable calculation easier?
Are two freshly returned structurally equal objects necessarily ===?
What is the exact console output in Pure functions and observable effects example 1?
function total(q,price){return q*price;} console.log(total(3,5),total(3,5));What is the exact console output in Pure functions and observable effects example 2?
let rate=2;const cost=n=>n*rate;console.log(cost(4));rate=3;console.log(cost(4));