Sub topic 1
Thinking Functionally: Declarative vs. Imperative Code
Prerequisites
This chapter assumes you know core JavaScript syntax, arrow functions, spread/rest syntax, and basic scope rules. You should be able to run code in Node.js or a browser console.
Declarative vs. Imperative
Imperative code spells out each step and changes state as it goes. Declarative code states what result you want and leaves the step-by-step control flow to functions. Functional programming leans declarative. It builds programs from small functions that take inputs and return outputs.
const prices = [10, 25, 40];
// Imperative: manage an index and an accumulator by hand
const doubledA = [];
for (let i = 0; i < prices.length; i++) {
doubledA.push(prices[i] * 2);
}
// Declarative: describe the transformation
const doubledB = prices.map((p) => p * 2);
console.log(doubledA, doubledB); // [ 20, 50, 80 ] [ 20, 50, 80 ]Functions as Values
JavaScript functions are first-class values. You can store them in variables, pass them as arguments, and return them from other functions. The call prices.map(...) above works because a function was passed in as data.
Closures: Functions That Remember
A closure is a function that keeps access to variables from the scope where it was created, even after that scope has finished running.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
console.log(makeCounter()()); // 1 (separate state)Pure Functions and Referential Transparency
A pure function returns the same output for the same input and has no side effects. Because of this, you can replace any call with its result without changing the program's behavior. That property is called referential transparency.
let total = 0;
function addToTotal(n) { total += n; return total; } // impure
function add(a, b) { return a + b; } // pure
console.log(addToTotal(5), addToTotal(5)); // 5 10
console.log(add(2, 3), add(2, 3)); // 5 5Managing Side Effects
A side effect is any change a function makes outside itself or any dependence on outside state. Logging, network calls, DOM updates, Date.now(), and Math.random() all count. A real program needs some side effects, so the goal is to isolate them rather than remove them. Keep your logic pure and push I/O to the edges of the program.
const formatGreeting = (name) => `Hello, ${name}!`; // pure core
console.log(formatGreeting('Ada')); // effect at the edgeExercise
Is const stamp = (msg) => ${Date.now()}: ${msg}; pure? How would you make it pure?
Show answer
It is impure because it reads the clock, so the same input gives different output. Make the time a parameter, as in const stamp = (msg, now) => ${now}: ${msg};, and call Date.now() at the edge of the program.