Pure Functions
Published by Brayan K
A pure function is one that always returns the same output for the same inputs and causes no side effects, meaning it never changes anything outside itself or depends on external state.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Ask what the caller can observe
A calculation is pure over its stated input domain when its result depends only on those inputs and it does not change pre-existing observable state. Merely returning a value or using map does not establish either condition. Here we inspect values, references and side effects separately, using fixed data rather than clocks or randomness.
function withCompleted(task) {
return { ...task, complete: true }; // Construct a result; do not assign task.complete.
}
const original = { id: "a", title: "Read arrays", complete: false };
const first = withCompleted(original);
const second = withCompleted(original);
console.log(first.complete, original.complete);
console.log(first === original, first === second); // Value equality is not object identity.
console.log(JSON.stringify(first) === JSON.stringify(second));
// ✅ Expected output:
// true false
// false false
// trueThe two results contain the same fields and values but are distinct objects. The identity comparisons make that distinction explicit. This simple record contains only primitive fields; nested sharing requires a separate decision. Functional Programming in JavaScript owns composing calculations into a workflow.
Deterministic output and absence of side effects are separate properties
const audit = [];
function double(value) {
audit.push(value);
return value * 2;
}
console.log(double(3), double(3));
console.log(audit.join(","));
// ✅ Expected output:
// 6 6
// 3,3Returning 6 both times does not make double pure: it changes an array that existed before each call. Logging, storage, network requests and changes to caller-owned objects are also observable effects. Effects are useful; the point is to place and name them deliberately.
let factor = 2;
function scale(value) { return value * factor; }
console.log(scale(3));
factor = 4;
console.log(scale(3));
function scaleExplicit(value, multiplier) { return value * multiplier; }
console.log(scaleExplicit(3, 2), scaleExplicit(3, 2));
// ✅ Expected output:
// 6
// 12
// 6 6A fixed immutable constant does not create the same problem as a changing dependency. The mistake here is an externally mutable factor. Read current time, randomness or mutable configuration at the boundary and pass the resulting value into a calculation when that fits the application.
let sequence = 0;
const nextNumber = () => ++sequence;
const stampWithProvider = (text, provider) => ({ text, number: provider() });
console.log(stampWithProvider("A", nextNumber).number, stampWithProvider("A", nextNumber).number);
const stampWithValue = (text, number) => ({ text, number });
console.log(JSON.stringify(stampWithValue("A", 7)) === JSON.stringify(stampWithValue("A", 7)));
// ✅ Expected output:
// 1 2
// trueDependency injection makes the provider visible and testable, but the first function still calls an effectful provider. Passing an already-obtained number isolates the calculation. The example uses an explicit counter, not a live clock.
Track the reference you actually mutate
const original = { name: "Mina", settings: { compact: false } };
const changed = { ...original };
changed.settings.compact = true;
console.log(changed === original, changed.settings === original.settings);
console.log(original.settings.compact);
// ✅ Expected output:
// false true
// trueconst original = {
name: "Mina",
settings: { compact: false, theme: "dark" },
profile: { country: "UK" }
};
const changed = { ...original, settings: { ...original.settings, compact: true } };
console.log(original.settings.compact, changed.settings.compact);
console.log(changed === original, changed.settings === original.settings);
console.log(changed.profile === original.profile);
// ✅ Expected output:
// false true
// false false
// trueOnly the path being changed needs new objects for this update contract. The unchanged profile is shared, so both callers must continue treating it as read-only. Deep Copy vs Shallow Copy & Data Structures owns cloning an entire supported object graph and its limits.
const source = [{ id: "A", rank: 2 }, { id: "B", rank: 1 }];
const sorted = [...source].sort((a, b) => a.rank - b.rank);
console.log(source.map(item => item.id).join(","), sorted.map(item => item.id).join(","));
console.log(sorted[0] === source[1]);
// ✅ Expected output:
// A,B B,A
// trueThis calculation only reorders references; it does not edit record fields, so a copied outer array is sufficient for that operation. Copying more data is not automatically safer if it obscures the intended sharing contract.
Freeze helps detect some writes; it does not create deep immutability
const settings = Object.freeze({ layout: { compact: false } });
settings.layout.compact = true;
console.log(Object.isFrozen(settings), Object.isFrozen(settings.layout));
console.log(settings.layout.compact);
try {
(function () { "use strict"; settings.layout = {}; })();
} catch (error) {
console.log(error.name);
}
// ✅ Expected output:
// true false
// true
// TypeErrorObject.freeze applies to the object passed to it. It does not recursively freeze nested values, and strict mode determines whether a forbidden assignment throws instead of silently failing. A frozen fixture is useful for checking an update function, but it is not a universal deep-copy or security mechanism.
function complete(task) {
"use strict";
task.complete = true;
return task;
}
complete(Object.freeze({ complete: false }));
// ✅ Expected error:
// TypeError: Cannot assign to read only property 'complete' of object '#<Object>'The exact expected error comes from the executed strict-mode program. A non-mutating update can accept this same frozen input because it reads the old record and returns a new one.
Local builders and deliberate no-op identity can both be valid
function frequencies(values) {
const result = new Map();
for (const value of values) result.set(value, (result.get(value) ?? 0) + 1);
return result;
}
const values = ["A", "B", "A"];
const result = frequencies(values);
console.log(result.get("A"), result.get("B"), values.join(","));
console.log(result === frequencies(values));
// ✅ Expected output:
// 2 1 A,B,A
// falseThe Map is allocated inside the function and changes only while the result is being built. The returned map is mutable afterward; the API must state whether callers may mutate it. Returning the same cached mutable object to unrelated callers would create a different sharing contract.
function setCompact(settings, compact) {
if (settings.compact === compact) return settings;
return { ...settings, compact };
}
const source = { compact: false, theme: "dark" };
console.log(setCompact(source, false) === source);
const changed = setCompact(source, true);
console.log(changed === source, changed.compact, source.compact);
// ✅ Expected output:
// true
// false true falseThe no-op result deliberately retains identity. The changed result has a new identity. Neither identity rule proves a function pure by itself; the function must still avoid mutating its input or reading a changing hidden dependency.
Do effects after the state calculation at an explicit boundary
const complete = task => ({ ...task, complete: true });
const before = { id: "a", complete: false };
const after = complete(before);
const notifications = [];
function notify(task) { notifications.push(task.id); }
notify(after);
console.log(before.complete, after.complete, notifications.join(","));
// ✅ Expected output:
// false true aThe updater can be checked without sending a message or writing storage. The surrounding workflow chooses when to notify and what to do if that effect fails. Pure calculations do not make external effects transactional, eliminate race conditions or guarantee a performance improvement. Error Handling and Async/Await Architecture & Best Practices own those failure and scheduling decisions.
Guided exercise: update the changed nested path
Fill the literal hints. Copy the outer state and the settings object, set compact to true, and keep the separate profile branch shared.
const state = { settings: { compact: false }, profile: { name: "Mina" } };
const next = {
...___, // 👉 replace ___ with state
settings: { ...state.___, compact: true } // 👉 replace ___ with settings
};
console.log(state.settings.compact, next.settings.compact);
console.log(next.profile === state.___); // 👉 replace ___ with profile
// ✅ Expected output:
// false true
// trueIndependent brief: update one task with an explicit no-op rule
Write updateTask(state, action) for a validated state containing a tasks array of unique string ids and task records with title and complete. The action is either a set-complete action with a boolean value, or a rename action with a non-empty trimmed string value; both identify a task by a string id. Reject an unknown type, invalid action value or missing id before changing anything.
If the requested value already matches, return state itself. Otherwise return a new state, a new tasks array and a new changed task; preserve the identities of every other task and state.settings. Never mutate the input. Check frozen input, two different changes, unchanged action, missing id, whitespace-only rename, wrong value type and unknown action type. Sharing unchanged nodes means consumers must keep treating those nodes as read-only.
function updateTask(state, action) {
if (action === null || typeof action !== "object" || typeof action.id !== "string") {
throw new TypeError("action must identify a task");
}
let field, value;
if (action.type === "set-complete") {
if (typeof action.value !== "boolean") throw new TypeError("complete must be boolean");
field = "complete"; value = action.value;
} else if (action.type === "rename") {
if (typeof action.value !== "string" || action.value.trim() === "") {
throw new TypeError("title must be a non-empty string");
}
field = "title"; value = action.value.trim();
} else {
throw new Error("unknown action type");
}
const index = state.tasks.findIndex(task => task.id === action.id);
if (index < 0) throw new Error("task not found");
if (state.tasks[index][field] === value) return state;
const tasks = state.tasks.slice();
tasks[index] = { ...tasks[index], [field]: value };
return { ...state, tasks };
}
const first = Object.freeze({ id: "a", title: "Arrays", complete: false });
const second = Object.freeze({ id: "b", title: "Objects", complete: false });
const state = Object.freeze({ tasks: Object.freeze([first, second]), settings: Object.freeze({ theme: "dark" }) });
const completed = updateTask(state, { type: "set-complete", id: "a", value: true });
console.log(state.tasks[0].complete, completed.tasks[0].complete);
console.log(completed !== state, completed.tasks !== state.tasks, completed.tasks[0] !== first);
console.log(completed.tasks[1] === second, completed.settings === state.settings);
const renamed = updateTask(completed, { type: "rename", id: "b", value: " Prototypes " });
console.log(renamed.tasks[1].title, completed.tasks[1].title);
console.log(updateTask(completed, { type: "set-complete", id: "a", value: true }) === completed);
for (const action of [
{ type: "rename", id: "missing", value: "A" },
{ type: "rename", id: "a", value: " " },
{ type: "set-complete", id: "a", value: "true" },
{ type: "delete", id: "a" }
]) {
try { updateTask(state, action); } catch (error) { console.log(error.name, error.message); }
}
console.log(state.tasks[0] === first, state.tasks[1] === second);
// ✅ Expected output:
// false true
// true true true
// true true
// Prototypes Objects
// true
// Error task not found
// TypeError title must be a non-empty string
// TypeError complete must be boolean
// Error unknown action type
// true trueReference notes
React’s purity guide describes avoiding changes to pre-existing state while allowing fresh local construction. The Object.freeze reference explains its shallow boundary. These ordinary JavaScript examples test values and references directly; they do not infer performance from a coding style.
Practice quiz
What does this complete program print? const input={value:1}; const output={...input,value:2}; console.log(input.value,output.value,input===output);
- 1 2 false
- 2 2 true
- 1 1 false
- 2 2 false
Answer: 1 2 false. The copied record changes only the output.
What does this complete program print? const input={nested:{value:1}}; const output={...input};output.nested.value=2; console.log(input.nested.value);
- 1
- 2
- undefined
- TypeError
Answer: 2. The shallow copy still shares the nested object.
What does this complete program print? const input=Object.freeze({nested:{value:1}}); input.nested.value=2; console.log(input.nested.value,Object.isFrozen(input.nested));
- 1 true
- 2 true
- 2 false
- 1 false
Answer: 2 false. Only the outer object was frozen.
What does this complete program print? let count=0; function double(n){count++;return n*2} console.log(double(3),double(3),count);
- 6 6 0
- 6 12 2
- 6 6 1
- 6 6 2
Answer: 6 6 2. The output repeats, but the external counter still changes.
What does this complete program print? const input=[{id:"A",rank:2},{id:"B",rank:1}]; const sorted=[...input].sort((a,b)=>a.rank-b.rank); console.log(input[0].id,sorted[0].id,sorted[0]===input[1]);
- A B true
- B B true
- A B false
- A A true
Answer: A B true. The outer order is copied while the records remain shared.
What does this complete program print? const set=(state,value)=>state.value===value?state:{...state,value}; const state={value:2}; console.log(set(state,2)===state,set(state,3)===state);
- false false
- true false
- true true
- false true
Answer: true false. The explicit no-op contract preserves identity only when nothing changes.
What does this complete program print? function build(values){const result=[];for(const value of values)result.push(value*2);return result} const values=[2];const a=build(values),b=build(values); console.log(values[0],a[0],a===b);
- 4 4 true
- 2 4 true
- 2 4 false
- 4 4 false
Answer: 2 4 false. Local builders produce separate results while leaving input unchanged.
What does this complete program print? const source={settings:{compact:false},profile:{name:"Mina"}}; const next={...source,settings:{...source.settings,compact:true}}; console.log(next.settings===source.settings,next.profile===source.profile);
- true true
- false false
- true false
- false true
Answer: false true. The changed settings branch is copied while the unchanged profile is intentionally shared.
Continue this course
- Previous: Higher-Order Functions & Currying
- Next: JavaScript Memory Management & Garbage Collection — How V8 allocates and collects memory, and how to avoid leaks
- Quick reference: JavaScript cheat sheet