Functional Programming in JavaScript: Pure Functions and Immutability
Functional programming (FP) is a style of writing code with small, predictable functions that take data in, return new data out, and change nothing else. You already use parts of it every time you call map, filter or reduce. For testers it matters twice: code written this way is far easier to unit test, and test code written this way avoids a whole class of flaky failures caused by one test changing data that another test relies on. In this lesson you will learn pure functions and side effects, immutability and the difference between shallow and deep copies, data pipelines with map, filter and reduce, functions that return functions (currying and partial application), and composing small functions with pipe.
📖 What You’ll Learn: what functional programming is, pure vs impure functions, side effects, why pure functions are easy to test, immutability, const vs Object.freeze, shallow vs deep copies with spread and structuredClone, non-mutating array methods, first-class and higher-order functions, declarative pipelines with map, filter and reduce, closures, currying and partial application, compose and pipe, and immutable test data.
🧪 Pure Functions and Side Effects
Definition: a pure function (1) always returns the same output for the same input, and (2) has no side effects: it does not change its arguments, global variables, files, the DOM or anything outside itself.
📄 pure.js
let taxRate = 0.18;
const cart = { items: [499, 799] };
// impure: depends on a global and changes its argument
function addTaxImpure(c) {
c.total = c.items.reduce((a, b) => a + b, 0) * (1 + taxRate);
return c.total;
}
// pure: everything it needs comes in as arguments, nothing is changed
const totalWithTax = (items, rate) => items.reduce((a, b) => a + b, 0) * (1 + rate);
console.log(addTaxImpure(cart), cart); // cart was modified!
taxRate = 0.05;
console.log(addTaxImpure(cart)); // same input, different output
console.log(totalWithTax(cart.items, 0.18), totalWithTax(cart.items, 0.18)); // always the same
⌨️ Terminal
node pure.js
🖥️ Output
1531.6399999999999 { items: [ 499, 799 ], total: 1531.6399999999999 }
1362.9
1531.6399999999999 1531.6399999999999
| Side effect | Example |
|---|---|
| Changing an argument | arr.push(x) on an array that was passed in |
| Changing outer state | Updating a global counter or module variable |
| I/O | Writing files, network requests, console.log, DOM updates |
| Hidden inputs | Reading Date.now(), Math.random() or environment variables inside the function |
Programs need side effects (otherwise they do nothing useful). The FP idea is to keep them at the edges, in a few clearly named functions, and make the core logic pure.
💡 Tip: Pure functions are the easiest code in the world to test: no setup, no mocks, no clean-up. Call the function with inputs and compare the output. When code is hard to test, it is usually because logic and side effects are mixed together.
🧊 Immutability: const, freeze and Copies
Immutability means never changing data in place: to “update”, create a new value. First, a common misunderstanding: const only stops reassigning the variable; the object itself can still change. Object.freeze stops changes to the object, but only at the top level:
📄 freeze.js
"use strict";
const config = { env: "staging", browsers: ["chromium"] };
config.env = "prod"; // allowed: const does not freeze the object
console.log(config.env);
const frozen = Object.freeze({ env: "staging", browsers: ["chromium"] });
try {
frozen.env = "prod"; // strict mode: throws
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
frozen.browsers.push("firefox"); // nested array is NOT frozen
console.log(frozen.browsers, Object.isFrozen(frozen), Object.isFrozen(frozen.browsers));
⌨️ Terminal
node freeze.js
🖥️ Output
prod
TypeError: Cannot assign to read only property 'env' of object '#<Object>'
[ 'chromium', 'firefox' ] true false
Updating without mutating
Use spread for objects and arrays, and the non-mutating array methods (map, filter, toSorted, with, concat):
📄 update.js
const user = { name: "Asha", roles: ["tester"], address: { city: "Pune" } };
const promoted = { ...user, roles: [...user.roles, "lead"] }; // new object, new array
const moved = { ...user, address: { ...user.address, city: "Mumbai" } }; // copy every level you change
console.log(user.roles, promoted.roles);
console.log(user.address.city, moved.address.city);
console.log(user.address === promoted.address); // shallow copy shares untouched nested objects
const scores = [70, 95, 82];
console.log(scores.toSorted((a, b) => a - b), scores.with(0, 75), scores.filter((s) => s > 80), scores);
⌨️ Terminal
node update.js
🖥️ Output
[ 'tester' ] [ 'tester', 'lead' ]
Pune Mumbai
true
[ 70, 82, 95 ] [ 75, 95, 82 ] [ 95, 82 ] [ 70, 95, 82 ]
Shallow vs deep copy
Spread makes a shallow copy: nested objects are shared. structuredClone makes a deep copy, including Dates, Maps and Sets (but not functions):
📄 clone.js
const original = { name: "fixture", tags: ["smoke"], created: new Date("2026-11-23T00:00:00Z") };
const shallow = { ...original };
const deep = structuredClone(original);
shallow.tags.push("CHANGED-BY-SHALLOW");
deep.tags.push("changed-by-deep");
console.log(original.tags); // the shallow copy changed the original!
console.log(deep.tags, deep.created instanceof Date);
const viaJson = JSON.parse(JSON.stringify(original)); // old trick: loses types
console.log(typeof viaJson.created);
⌨️ Terminal
node clone.js
🖥️ Output
[ 'smoke', 'CHANGED-BY-SHALLOW' ]
[ 'smoke', 'changed-by-deep' ] true
string
🔁 Functions as Values and Declarative Pipelines
In JavaScript, functions are first-class values: you can store them, pass them and return them. A higher-order function takes or returns functions. This allows declarative code, describing what you want rather than how to loop:
📄 pipeline.js
const results = [
{ test: "login", status: "passed", ms: 1200 },
{ test: "cart", status: "failed", ms: 3400 },
{ test: "search", status: "passed", ms: 800 },
{ test: "pay", status: "failed", ms: 5100 },
];
// imperative: how to do it, step by step
let slowFailures = [];
for (let i = 0; i < results.length; i++) {
if (results[i].status === "failed" && results[i].ms > 3000) {
slowFailures.push(results[i].test.toUpperCase());
}
}
console.log(slowFailures);
// declarative: what we want
const isFailed = (r) => r.status === "failed";
const isSlow = (r) => r.ms > 3000;
console.log(results.filter(isFailed).filter(isSlow).map((r) => r.test.toUpperCase()));
// reduce builds any shape you need
const summary = results.reduce(
(acc, r) => ({ ...acc, [r.status]: (acc[r.status] ?? 0) + 1, totalMs: acc.totalMs + r.ms }),
{ totalMs: 0 }
);
console.log(summary);
⌨️ Terminal
node pipeline.js
🖥️ Output
[ 'CART', 'PAY' ]
[ 'CART', 'PAY' ]
{ totalMs: 10500, passed: 2, failed: 2 }
💡 Tip: Name your small predicates (isFailed, isSlow). The pipeline then reads like a sentence, and each predicate can be unit tested on its own.
🍛 Closures, Currying and Partial Application
A function that returns a function remembers the variables it was created with (a closure, see Module 4). That lets you build specialised functions from general ones:
📄 curry.js
// partial application: fix some arguments now, pass the rest later
const request = (method, baseURL, path) => `${method} ${baseURL}${path}`;
const stagingGet = (path) => request("GET", "https://staging.example.com", path);
console.log(stagingGet("/api/users"));
// currying: a function of many arguments becomes a chain of one-argument functions
const hasStatus = (status) => (result) => result.status === status;
const longerThan = (ms) => (result) => result.ms > ms;
const results = [{ status: "failed", ms: 4000 }, { status: "passed", ms: 100 }, { status: "failed", ms: 200 }];
console.log(results.filter(hasStatus("failed")).length);
console.log(results.filter(longerThan(1000)).length);
// a generic curry helper
const curry = (fn) => function curried(...args) {
return args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
};
const between = curry((min, max, n) => n >= min && n <= max);
const isValidAge = between(18, 60);
console.log([17, 18, 60, 61].map(isValidAge));
⌨️ Terminal
node curry.js
🖥️ Output
GET https://staging.example.com/api/users
2
1
[ false, true, true, false ]
🔗 Compose and Pipe
Composition builds a new function from small ones, where each output becomes the next input. pipe applies them left to right (easiest to read); compose applies them right to left, as in mathematics:
📄 pipe.js
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const collapseSpaces = (s) => s.replace(/\s+/g, " ");
const slugify = (s) => s.replace(/[^a-z0-9 ]/g, "").replaceAll(" ", "-");
const toSlug = pipe(trim, lower, collapseSpaces, slugify);
console.log(toSlug(" Login Page: Valid User! "));
const normaliseText = compose(collapseSpaces, lower, trim); // same order as pipe(trim, lower, collapseSpaces)
console.log(JSON.stringify(normaliseText(" Order PLACED ")));
// typical tester use: normalise UI text before comparing
const sameText = (a, b) => normaliseText(a) === normaliseText(b);
console.log(sameText("Welcome,\n Asha", "welcome, asha"));
⌨️ Terminal
node pipe.js
🖥️ Output
login-page-valid-user
"order placed"
true
🧪 Tester Scenario: Immutable Test Data with Builders
Shared, mutable fixtures cause tests that pass alone but fail together. A frozen base object plus pure “with” functions gives every test its own data, and the base can never be changed by accident:
📄 builders.js
const deepFreeze = (obj) => {
Object.values(obj).forEach((v) => typeof v === "object" && v !== null && deepFreeze(v));
return Object.freeze(obj);
};
const BASE_USER = deepFreeze({
name: "Test User",
email: "user@sqatools.in",
roles: ["viewer"],
address: { city: "Pune", pin: "411001" },
});
// pure helpers: each returns a NEW user
const withRole = (role) => (u) => ({ ...u, roles: [...u.roles, role] });
const withEmail = (email) => (u) => ({ ...u, email });
const withCity = (city) => (u) => ({ ...u, address: { ...u.address, city } });
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const admin = pipe(withRole("admin"), withEmail("admin@sqatools.in"))(BASE_USER);
const mumbaiUser = withCity("Mumbai")(BASE_USER);
console.log(admin.roles, admin.email);
console.log(mumbaiUser.address);
console.log("base unchanged:", BASE_USER.roles, BASE_USER.address.city);
try {
BASE_USER.roles.push("hacker"); // a careless test tries to modify the fixture (push throws on frozen arrays)
} catch (e) {
console.log(`blocked: ${e.name}: ${e.message}`);
}
⌨️ Terminal
node builders.js
🖥️ Output
[ 'viewer', 'admin' ] admin@sqatools.in
{ city: 'Mumbai', pin: '411001' }
base unchanged: [ 'viewer' ] Pune
blocked: TypeError: Cannot add property 1, object is not extensible
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Rewrite this impure function as a pure one.
let count = 0;
function addVisit(list, page) { list.push(page); count++; return list; }Show answer
📄 practice1.js
const addVisit = (list, page) => [...list, page];
const before = ["home"];
const after = addVisit(before, "cart");
console.log(before, after, after.length);🖥️ Output
[ 'home' ] [ 'home', 'cart' ] 2Q2. Update the status of order 2 to “shipped” without changing the original array.
Show answer
📄 practice2.js
const orders = [{ id: 1, status: "new" }, { id: 2, status: "new" }];
const updated = orders.map((o) => (o.id === 2 ? { ...o, status: "shipped" } : o));
console.log(orders[1].status, updated[1].status, orders[0] === updated[0]);🖥️ Output
new shipped trueQ3. Make a deep copy of a config with a nested timeouts object, change the copy, and show the original is unchanged.
Show answer
📄 practice3.js
const config = { env: "qa", timeouts: { action: 5000, test: 30000 } };
const copy = structuredClone(config);
copy.timeouts.action = 1000;
console.log(config.timeouts.action, copy.timeouts.action);🖥️ Output
5000 1000Q4. Use one reduce to compute the average duration of the passed tests.
Show answer
📄 practice4.js
const runs = [{ s: "passed", ms: 100 }, { s: "failed", ms: 900 }, { s: "passed", ms: 300 }];
const { sum, n } = runs.filter((r) => r.s === "passed").reduce((a, r) => ({ sum: a.sum + r.ms, n: a.n + 1 }), { sum: 0, n: 0 });
console.log(sum / n);🖥️ Output
200Q5. Write a curried startsWith(prefix)(text) and use it to filter test names starting with “api_”.
Show answer
📄 practice5.js
const startsWith = (prefix) => (text) => text.startsWith(prefix);
console.log(["api_users", "ui_login", "api_orders"].filter(startsWith("api_")));🖥️ Output
[ 'api_users', 'api_orders' ]Q6. Build pipe and use it to turn ” Hello QA ” into “HELLO_QA”.
Show answer
📄 practice6.js
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const format = pipe((s) => s.trim(), (s) => s.toUpperCase(), (s) => s.replaceAll(" ", "_"));
console.log(format(" Hello QA "));🖥️ Output
HELLO_QA🧠 MCQ Quiz: Functional Programming
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which is a property of a pure function?Answer: Same input always gives the same output, with no side effects. Determinism plus no side effects.
- Which of these is a side effect?Answer: Changing an array that was passed in. Mutation of inputs or outer state.
- What does
constprevent?Answer: Reassigning the variable. Use Object.freeze to stop property changes. - How deep does
Object.freezego?Answer: Only the top level. Nested objects need their own freeze. - Which creates a deep copy that keeps Date objects as Dates?Answer: structuredClone(obj). The JSON trick turns dates into strings.
- What is a higher-order function?Answer: A function that takes or returns a function. map, filter and reduce are examples.
- What does currying do?Answer: Turns f(a, b, c) into f(a)(b)(c). Each call returns a function waiting for the next argument.
- In what order does
pipe(f, g, h)(x)apply the functions?Answer: f, then g, then h. compose applies right to left. - Why are pure functions easy to test?Answer: No setup or mocks: call with inputs and check the output. Determinism makes tests simple and stable.
- Which array method does NOT mutate the array?Answer: map. Also filter, concat, toSorted, with.
💼 Interview Questions and Answers
Q1. What is a pure function and why does it matter?
A pure function returns the same result for the same arguments and causes no side effects. It is predictable, easy to reason about, safe to cache (memoize) and run in parallel, and trivial to unit test because it needs no environment. Keeping business logic pure and isolating side effects (I/O, DOM, network) at the edges makes the whole codebase more testable.
Q2. How do you avoid shared mutable state in test code?
Create fresh data per test (factory or builder functions), freeze shared constants, use non-mutating operations (spread, map, toSorted, structuredClone) instead of push/sort/splice on shared arrays, and avoid module-level variables that tests change. In Playwright, fixtures give each test its own instance, and tests run in isolated browser contexts.
Q3. Shallow copy vs deep copy?
A shallow copy ({ ...obj }, [...arr], Object.assign) duplicates only the top level; nested objects are still shared, so changing them affects the original. A deep copy duplicates every level; structuredClone does this and preserves Dates, Maps, Sets and circular references, while JSON.parse(JSON.stringify()) loses those types and functions.
Q4. What is the difference between compose and pipe?
Both combine functions so the output of one is the input of the next. pipe(f, g)(x) is g(f(x)), reading left to right in execution order; compose(f, g)(x) is f(g(x)), right to left like mathematical notation. They are usually built with reduce and reduceRight.
❓ Frequently Asked Questions
🤔 Is JavaScript a functional language?
It is multi-paradigm: it supports object-oriented, imperative and functional styles. First-class functions and closures make functional techniques natural, and most modern codebases mix styles.
🤔 Does immutability make code slower?
Copying has a cost, but for typical data sizes it is negligible compared with the bugs it prevents. For very large or hot data, libraries such as Immer use structural sharing to keep copies cheap.
🤔 Should all my code be pure?
No. Programs need side effects to be useful. Aim for a pure core (calculations, validation, transformations) and a thin layer that performs I/O.
🤔 What are libraries for functional programming in JavaScript?
Ramda and lodash/fp provide curried helpers and composition; Immer simplifies immutable updates. Plain modern JavaScript covers most needs without them.
🏁 Summary
- Pure functions: same input, same output, no side effects. They are the easiest code to test.
conststops reassignment;Object.freezestops top-level changes; copy instead of mutating.- Spread gives shallow copies;
structuredClonegives deep copies with Dates, Maps and Sets. - Higher-order functions and named predicates make declarative pipelines with map, filter and reduce.
- Closures enable currying and partial application;
pipe/composecombine small functions; builders give each test immutable data.
Next, continue with Lesson 65: Dates, Times and Intl.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in