Functional Programming
Published by Brayan K
Functional programming is a style of writing code that builds programs by composing pure functions, avoiding shared state and mutable data, and treating functions as values you can pass around and combine.
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.
Build a workflow from named input-to-output steps
Functional programming becomes useful when a reader can follow the data contract of each step. A stage receives one value, produces the value the following stage expects, and leaves caller-owned data intact. It is not a rule that every line must use an arrow, every loop must become recursion, or every function must be pure.
const rows = [
{ title: " Arrays ", minutes: 8, complete: false },
{ title: "Functions", minutes: 12, complete: true },
{ title: " Objects ", minutes: 10, complete: false }
];
const normalize = list => list.map(row => ({ ...row, title: row.title.trim() }));
const unfinished = list => list.filter(row => row.complete === false);
const summarize = list => ({
titles: list.map(row => row.title),
minutes: list.reduce((total, row) => total + row.minutes, 0)
});
const normalized = normalize(rows); // Records still have title, minutes and complete.
const selected = unfinished(normalized); // Still an array of records.
const report = summarize(selected); // Now one report object.
console.log(report.titles.join(", "), report.minutes);
console.log(rows[0].title === " Arrays ", Object.hasOwn(rows[0], "minutes"));
// ✅ Expected output:
// Arrays, Objects 18
// true trueThe stage names describe their role and the intermediate values make the shape changes visible. This example assumes valid records; a later boundary makes that assumption explicit. map, filter & reduce owns the array-method mechanics. Pure Functions, Immutability & Side Effects owns deciding whether a function actually leaves external state unchanged.
Pure functions can still produce different answers when reordered
const numbers = [4, 6];
const double = value => value * 2;
const aboveTen = value => value > 10;
console.log(numbers.map(double).filter(aboveTen).join(","));
console.log(numbers.filter(aboveTen).map(double).join(","));
console.log(numbers.join(","));
// ✅ Expected output:
// 12
//
// 4,6Both callbacks are pure, but the first pipeline asks whether doubled values exceed ten and the second asks whether original values do. Purity makes a calculation easier to repeat and inspect; it does not make arbitrary stages commute. Check the required meaning before moving a filter, rounding step or validation boundary.
const summarize = values => ({ count: values.length });
const selected = summarize([1, 2, 3]);
console.log(selected.filter(value => value > 1));
// ✅ Expected error:
// TypeError: selected.filter is not a functionWrite down stage shapes before composing them: array of records, then array of records, then report object. A function’s existence is not proof its output matches the next function’s input. TypeScript can express many such contracts; runtime validation is still needed for values from outside the trusted boundary.
A pipeline does not make its callbacks pure
const rows = [{ title: " Arrays " }];
const result = rows.map(row => {
row.title = row.title.trim();
return row;
});
console.log(result === rows, result[0] === rows[0]);
console.log(rows[0].title);
// ✅ Expected output:
// false true
// ArraysThe array method returns a new array, but this callback mutates an element shared with the input. Copying the record you change is the relevant boundary. Deep Copy vs Shallow Copy & Data Structures owns copying nested graphs; a blanket “map is immutable” statement is insufficient.
let limit = 10;
const hiddenPolicy = minutes => minutes <= limit;
console.log(hiddenPolicy(12));
limit = 15;
console.log(hiddenPolicy(12));
const withinLimit = (minutes, maximum) => minutes <= maximum;
console.log(withinLimit(12, 10), withinLimit(12, 10));
// ✅ Expected output:
// false
// true
// false falseThe explicit version makes the relevant policy part of the input. The example uses fixed numbers rather than a clock or random value. Passing dependencies makes them visible; it does not automatically remove side effects from a function dependency that you pass in.
Keep invalid data separate from valid zero and empty results
const minutes = [0, 5, undefined];
console.log(minutes.filter(Boolean).join(","));
console.log(minutes.filter(value => typeof value === "number").join(","));
// ✅ Expected output:
// 5
// 0,5The right predicate depends on the contract. Zero can be meaningful in a progress report even if a playlist track must have a positive duration. Do not silently use truthiness as a general validation policy.
function readMinutes(value) {
if (!Number.isInteger(value) || value < 0) return { ok: false, error: "invalid minutes" };
return { ok: true, value };
}
for (const input of [0, 5, -1, "5"]) {
const result = readMinutes(input);
console.log(result.ok ? "minutes:" + result.value : result.error);
}
// ✅ Expected output:
// minutes:0
// minutes:5
// invalid minutes
// invalid minutesThis function returns a tagged result rather than throwing because invalid input is part of its ordinary input contract. Other boundaries may throw. Choose one shape and make the next stage handle it explicitly; do not mix a number, undefined and an error string as indistinguishable success values. Error Handling owns exception boundaries.
Local mutation can implement a predictable calculation
function upperNames(names) {
const result = [];
for (const name of names) result.push(name.toUpperCase());
return result;
}
const names = ["Mina", "Leo"];
const first = upperNames(names);
const second = upperNames(names);
console.log(first.join(","), second.join(","));
console.log(first === second, names.join(","));
// ✅ Expected output:
// MINA,LEO MINA,LEO
// false Mina,Leoresult is created inside the call and is not shared with the caller until it is returned. Building it with push does not mutate the input. The important boundary is observable state, not whether the implementation contains a loop or an assignment. Returning a new object also need not mean every repeated call returns the same identity; equivalent result values can be separately allocated.
function withLoop(values) {
let total = 0;
for (const value of values) if (value > 0) total += value * 2;
return total;
}
const withMethods = values => values.filter(value => value > 0).map(value => value * 2).reduce((sum, value) => sum + value, 0);
for (const values of [[], [-2, 0], [-1, 2, 3]]) {
console.log(withLoop(values), withMethods(values));
}
// ✅ Expected output:
// 0 0
// 0 0
// 10 10This comparison establishes the results for these fixtures, not a universal speed ranking. A multi-stage array pipeline may allocate intermediate arrays; a loop may express an early exit more directly. Performance Optimization owns measurement. Recursion & the Call Stack owns recursion rather than treating it as mandatory replacement syntax for loops.
Keep the calculation separate from the effect that uses it
const summarize = values => ({ count: values.length, total: values.reduce((sum, value) => sum + value, 0) });
function runReport(values, send) {
const report = summarize(values);
send(report);
return report;
}
const sent = [];
const report = runReport([2, 3], value => sent.push(value));
console.log(report.count, report.total);
console.log(sent.length, sent[0] === report);
// ✅ Expected output:
// 2 5
// 1 truesummarize is a calculation over the stated numeric input. runReport deliberately performs an effect through send and is not described as pure. Its injected recorder lets this example verify what was sent without a real network request. A failing sender can still fail the workflow; an abstraction name does not erase that failure.
function runReport(values, send) {
const report = { count: values.length };
send(report);
return report;
}
runReport([], () => { throw new Error("report delivery failed"); });
// ✅ Expected error:
// Error: report delivery failedComposing functions does not move CPU work onto another thread, remove the need for error handling, or guarantee fewer bugs. It makes dependencies and transformations easier to inspect when the contracts are kept small and explicit. Higher-Order Functions & Currying owns function adapters, currying and composition helpers.
Guided exercise: preserve the shapes between stages
Fill the literal hints. Normalize each title into a new record, keep incomplete records, then calculate total minutes with an explicit empty-list identity.
const rows = [{ title: " A ", minutes: 3, complete: false }, { title: "B", minutes: 5, complete: true }];
const normalized = rows.map(row => ({ ...row, title: row.title.___() })); // 👉 replace ___ with trim
const selected = normalized.filter(row => row.complete === ___); // 👉 replace ___ with false
const total = selected.reduce((sum, row) => sum + row.minutes, ___); // 👉 replace ___ with 0
console.log(selected.map(row => row.title).join(","), total);
console.log(rows[0].title === " A ");
// ✅ Expected output:
// A 3
// trueIndependent brief: plan a playlist in input order
Write planPlaylist(tracks, budget). Validate a plain array of records with unique non-empty string ids, non-empty string titles, integer minutes from 1 to 120, and a boolean enabled. Trim ids and titles, rejecting duplicate trimmed ids. Validate every record even if disabled. budget is an integer from 0 to 240. Return titles, totalMinutes and unusedMinutes.
After normalization, exclude disabled tracks. Walk the enabled tracks in input order and accept a prefix: stop at the first track that would exceed the budget, even if a later short track would fit. Do not change any input record. Check an exact fit, zero budget, an empty list, a too-large first track, disabled tracks, invalid disabled data and duplicate ids.
function normalizeTracks(tracks) {
if (!Array.isArray(tracks)) throw new TypeError("tracks must be an array");
const ids = new Set();
return Array.from(tracks, track => {
if (track === null || typeof track !== "object" ||
typeof track.id !== "string" || track.id.trim() === "" ||
typeof track.title !== "string" || track.title.trim() === "" ||
!Number.isInteger(track.minutes) || track.minutes < 1 || track.minutes > 120 ||
typeof track.enabled !== "boolean") {
throw new TypeError("invalid track");
}
const id = track.id.trim();
if (ids.has(id)) throw new Error("duplicate track id");
ids.add(id);
return { id, title: track.title.trim(), minutes: track.minutes, enabled: track.enabled };
});
}
function packPrefix(tracks, budget) {
const titles = [];
let totalMinutes = 0;
for (const track of tracks) {
if (totalMinutes + track.minutes > budget) break;
titles.push(track.title);
totalMinutes += track.minutes;
}
return { titles, totalMinutes, unusedMinutes: budget - totalMinutes };
}
function planPlaylist(tracks, budget) {
if (!Number.isInteger(budget) || budget < 0 || budget > 240) {
throw new RangeError("budget must be an integer from 0 to 240");
}
const normalized = normalizeTracks(tracks);
const enabled = normalized.filter(track => track.enabled);
return packPrefix(enabled, budget);
}
const tracks = [
{ id: " a ", title: " Arrays ", minutes: 8, enabled: true },
{ id: "b", title: "Skipped", minutes: 5, enabled: false },
{ id: "c", title: "Objects", minutes: 10, enabled: true },
{ id: "d", title: "Short", minutes: 2, enabled: true }
];
const before = JSON.stringify(tracks);
for (const budget of [18, 10, 0, 7]) console.log(JSON.stringify(planPlaylist(tracks, budget)));
console.log(JSON.stringify(planPlaylist([], 20)));
console.log("unchanged", JSON.stringify(tracks) === before);
for (const invalid of [
[{ ...tracks[0], enabled: false, minutes: -1 }],
[tracks[0], { ...tracks[0], id: "a" }],
[undefined]
]) {
try { planPlaylist(invalid, 20); } catch (error) { console.log(error.message); }
}
try { planPlaylist(tracks, -1); } catch (error) { console.log(error.message); }
// ✅ Expected output:
// {"titles":["Arrays","Objects"],"totalMinutes":18,"unusedMinutes":0}
// {"titles":["Arrays"],"totalMinutes":8,"unusedMinutes":2}
// {"titles":[],"totalMinutes":0,"unusedMinutes":0}
// {"titles":[],"totalMinutes":0,"unusedMinutes":7}
// {"titles":[],"totalMinutes":0,"unusedMinutes":20}
// unchanged true
// invalid track
// duplicate track id
// invalid track
// budget must be an integer from 0 to 240Reference notes
The first-class function reference describes functions as values. The reduce reference specifies its accumulator contract. React’s purity guide explains the distinction between changing pre-existing data and constructing fresh local results; this lesson’s examples are ordinary JavaScript, not React execution tests.
Practice quiz
What does this complete program print? const values=[4,6]; console.log(values.map(x=>x*2).filter(x=>x>10).join(","));
- 12
- No output
- 8,12
- 4,6
Answer: 12. The threshold is applied after doubling, so only 12 qualifies.
What does this complete program print? const values=[4,6]; console.log(JSON.stringify(values.filter(x=>x>10).map(x=>x*2)));
- [12]
- []
- [8,12]
- [4,6]
Answer: []. Filtering original values first removes both; purity does not make the order interchangeable.
What does this complete program print? const source=[{value:1}]; const result=source.map(item=>{item.value++;return item}); console.log(result===source,source[0].value);
- true 2
- false 1
- false 2
- true 1
Answer: false 2. The new outer array still contains the mutated source object.
What does this complete program print? const values=[0,2]; console.log(values.filter(Boolean).join(","));
- 0,2
- 0
- undefined
- 2
Answer: 2. Zero is falsy and is removed by this predicate.
What does this complete program print? function twice(values){const result=[];for(const value of values)result.push(value*2);return result;} const input=[2,3]; console.log(twice(input).join(","),input.join(","));
- 4,6 2,3
- 4,6 4,6
- 2,3 2,3
- 2,3 4,6
Answer: 4,6 2,3. The function builds a fresh local result without changing input.
What does this complete program print? const total=values=>values.reduce((sum,value)=>sum+value,0); console.log(total([]));
- undefined
- 0
- TypeError
- NaN
Answer: 0. The explicit initial value defines the empty-input result.
What does this complete program print? let threshold=5; const keep=value=>value>threshold; console.log(keep(6));threshold=10;console.log(keep(6));
- true true
- false false
- true false
- false true
Answer: true false. A changing outer dependency changes the result for the same explicit argument.
What does this complete program print? const summarize=values=>({count:values.length}); const a=summarize([1]),b=summarize([1]); console.log(a.count===b.count,a===b);
- true true
- false false
- false true
- true false
Answer: true false. Equivalent returned values can be stored in distinct newly allocated objects.
Continue this course
- Previous: Prototype Chain & Advanced OOP Patterns
- Next: Higher-Order Functions & Currying — Pass, return, and partially apply functions to build powerful abstractions
- Quick reference: JavaScript cheat sheet