Sub topic 1
Thinking Functionally: Declarative vs. Imperative Code
Functional programming (FP) is a way of building programs out of small functions that take input and return output, without changing anything around them. JavaScript is not a purely functional language. It does give you the tools FP needs, though: functions you can pass around like any other value, closures, and array methods such as map and filter. This chapter covers the mindset behind those tools. The chapter's main point is that you can describe what result you want instead of spelling out how to compute it, step by step.
Prerequisites
This chapter assumes you are comfortable with:
- Core JavaScript syntax: variables, functions, objects, and arrays
- Arrow functions such as
(x) => x * 2and the spread/rest syntax... - Basic scope rules, including the difference between
letandconst - Running a script with
node file.jsor pasting code into a browser console
You do not need any prior FP experience. Later chapters explain each term used here in detail.
Two Ways to Describe the Same Computation
Imperative code gives the computer a sequence of commands. It creates a variable, loops over an index, checks a condition, and pushes onto an array. You follow along by simulating the machine in your head.
Declarative code describes the relationship between input and output. It says "keep the adults, then take their names in upper case" and leaves the loop mechanics to the language.
const users = [
{ name: 'Ada', age: 36 },
{ name: 'Linus', age: 17 },
{ name: 'Grace', age: 45 }
];
// Imperative: describe each step
const adultNamesImperative = [];
for (let i = 0; i < users.length; i++) {
if (users[i].age >= 18) {
adultNamesImperative.push(users[i].name.toUpperCase());
}
}
// Declarative: describe the result
const adultNames = users
.filter((u) => u.age >= 18)
.map((u) => u.name.toUpperCase());
console.log(adultNamesImperative); // [ 'ADA', 'GRACE' ]
console.log(adultNames); // [ 'ADA', 'GRACE' ]Both versions produce the same array. The imperative version has a loop counter, a mutable accumulator, and an index lookup repeated three times, and each of those is a place where a bug can hide. Off-by-one errors and wrong indexes are typical. The declarative version has none of these. Each step reads as one sentence.
| Aspect | Imperative | Declarative / functional |
|---|---|---|
| Focus | How to compute | What to compute |
| State | Variables updated over time | New values derived from old ones |
| Building blocks | Statements (`for`, `if`, assignment) | Expressions and function calls |
| Reading the code | Trace execution step by step | Read each transformation on its own |
| Typical bugs | Off-by-one, stale or shared state | Wrong order of steps, unexpected copies |
The Core Ideas
Functional style in JavaScript rests on a few connected ideas. Each one gets its own chapter later.
- Functions are values. You can store a function in a variable, pass it as an argument, and return it from another function.
filterandmapabove both take a function as their argument. - Pure functions. A pure function's output depends only on its inputs, and calling it changes nothing outside the function. Pure functions are easy to test, cache, and reorder.
- Immutability. Instead of changing an existing object or array, you create a new one that holds the change.
- Composition. You build larger behavior by connecting small functions so that each one's output feeds the next one's input.
These ideas support one another. Composition is only safe when functions are pure, and functions can only stay pure when the data they receive is never mutated.
Prefer Expressions Over Statements
A statement performs an action, such as if, for, or an assignment. An expression produces a value. Functional code leans on expressions because a value can be passed, returned, and combined, and an action cannot.
// Statement-based: declare, then assign in branches
function shippingCostImperative(total) {
let cost;
if (total >= 50) {
cost = 0;
} else {
cost = 5;
}
return cost;
}
// Expression-based: the whole body is one value
const shippingCost = (total) => (total >= 50 ? 0 : 5);
console.log(shippingCostImperative(60), shippingCost(60)); // 0 0
console.log(shippingCostImperative(20), shippingCost(20)); // 5 5The expression version has no variable that sits in an undefined state partway through the function. Because it never reassigns anything, you could also have written it with const alone.
Why Shared State Makes Code Hard to Reason About
Most of the trouble with imperative code comes from state that changes over time and is visible to more than one part of the program. The example below looks harmless:
const scores = [72, 95, 88];
// Mutates its argument: Array.prototype.sort sorts in place
function topScoreMutating(list) {
return list.sort((a, b) => b - a)[0];
}
console.log(topScoreMutating(scores)); // 95
console.log(scores); // [ 95, 88, 72 ] (caller's array reordered)
// Leaves its argument alone
function topScore(list) {
return Math.max(...list);
}
const fresh = [72, 95, 88];
console.log(topScore(fresh)); // 95
console.log(fresh); // [ 72, 95, 88 ]The caller asked a question ("what is the top score?") and got its data rearranged as a hidden side effect. Any other code that relied on the original order is now broken, and the bug shows up far from where it was caused. Functional style removes this whole category of bug by refusing to mutate inputs.
Common Errors When Starting Out
Using `map` for side effects
map exists to build a new array. If your callback only logs or writes somewhere, use forEach, or better, a plain loop at the edge of your program.
const ids = [1, 2, 3];
const wrong = ids.map((id) => { console.log(id); }); // logs 1, 2, 3
console.log(wrong); // [ undefined, undefined, undefined ]
ids.forEach((id) => console.log(id)); // intent is clear: an effect, no resultBelieving `const` means immutable
const stops you from reassigning the variable. It does not stop you from changing the object the variable points to.
const config = { debug: false };
config.debug = true; // allowed
console.log(config.debug); // true
const frozen = Object.freeze({ debug: false });
frozen.debug = true; // silently ignored (throws in strict mode)
console.log(frozen.debug); // falseObject.freeze is shallow: it freezes only the top level, so nested objects stay mutable.
Treating "functional" as "no loops ever"
Declarative methods still loop internally. A chain of filter, map, and reduce makes three passes over the data and allocates an intermediate array at each step. That cost rarely matters, but on very large arrays in hot code paths, a single well-named loop inside a pure function can be the better choice. The function stays pure even though its body is imperative.
JavaScript Is Multi-Paradigm
You do not have to choose between styles for a whole codebase. A practical approach:
- Keep the core logic (calculations, validation, data shaping) pure and declarative.
- Push effects such as network calls, DOM updates, logging, and timers to the edges of the program.
- Use a local, unexported mutable variable when it makes a function clearer or faster, as long as callers cannot observe it.
The rest of this tutorial builds the tools for that approach, starting with functions as values.
Exercise
Rewrite this imperative code declaratively, without mutating prices, and state what it returns: const prices = [12, 48, 7, 30]; const result = []; for (let i = 0; i < prices.length; i++) { if (prices[i] > 10) result.push(prices[i] * 1.2); }
Show answer
const result = prices.filter((p) => p > 10).map((p) => p * 1.2); It returns approximately [14.4, 57.6, 36] (floating-point rounding may show 57.599999999999994 for 48 * 1.2). The original prices array is unchanged.
Exercise
A teammate writes const latest = (posts) => posts.reverse()[0]; to get the newest post from a chronologically ordered array. What is wrong with it, and how would you fix it?
Show answer
reverse mutates the array in place, so every call flips the caller's posts and alternate calls return different posts. Fix it without mutation: const latest = (posts) => posts[posts.length - 1]; or posts.at(-1). If you really need a reversed copy, use posts.toReversed().
Exercise
Is a function that uses a for loop and a local let accumulator internally necessarily impure? Explain.
Show answer
No. Purity depends on what callers can observe. If the function reads only its arguments, changes only local variables it created, and returns the same output for the same input, it is pure even though its body is imperative.