JavaScript, lesson 14
In JavaScript, functions are values, just like numbers and strings. You can store them in variables, put them in arrays, pass them to other functions and return them from functions. This one idea, together with closures, is behind much of the language's character, from array methods to event handlers.
A higher-order function takes a function as an argument or returns one. The array methods are the ones you will use every day:
const prices = [4, 12, 7, 30];
const withTax = prices.map((p) => p * 1.2); // transform each element
const cheap = prices.filter((p) => p < 10); // keep elements that pass a test
const total = prices.reduce((sum, p) => sum + p, 0); // combine into one value
const anyBig = prices.some((p) => p > 20); // true if at least one passes
const allPositive = prices.every((p) => p > 0); // true if all pass
console.log(cheap, total, anyBig, allPositive); // [ 4, 7 ] 53 true truereduce deserves a closer look. It walks the array carrying an accumulator. The callback
receives the accumulator and the current element and returns the new accumulator. The second
argument (0 here) is the starting value. Always give one; without it, reduce on an empty
array throws.
These methods do not change the original array, and they chain nicely:
Each callback also receives the index as a second argument, as in forEach((item, i) => ...).
A function can use variables from the place where it was written. When an inner function outlives the outer function call, it keeps those variables alive. That combination of a function and the variables it remembers is a closure:
Every call to makeCounter creates a new count, so a and b each have their own. Nothing
outside can touch count except through the returned function: closures give you private
state without a class.
Returning functions lets you build specialised functions from general ones:
You can also combine functions. pipe takes several functions and returns one that runs them
in order, feeding each result into the next:
...fns is a rest parameter: it gathers all arguments into an array.
Closures capture the variable, not a snapshot of its value. With let in a for loop, each
round gets a fresh variable, so callbacks created in the loop each see their own value. The old
var keyword shares one variable across all rounds, and every callback would see the final
value. One more reason to stick to let and const.
2 exercises to try what you just read.
const report = prices
.filter((p) => p >= 7)
.map((p) => `$${p}`)
.join(", "); // "$12, $7, $30"function makeCounter() {
let count = 0; // private to this counter
return () => {
count += 1;
return count;
};
}
const a = makeCounter();
const b = makeCounter();
a(); a();
console.log(a(), b()); // 3 1const multiplier = (factor) => (n) => n * factor;
const double = multiplier(2);
const triple = multiplier(3);
console.log([1, 2, 3].map(triple)); // [ 3, 6, 9 ]const pipe = (...fns) => (x) => fns.reduce((value, fn) => fn(value), x);
const process = pipe(double, (n) => n + 1, String);
console.log(process(5)); // "11"ana 20.50 paid
ben 75 paid
cy 99 pending
ben 60 paid
dee 50 paidpaid total: 205.50
pending: 1
big spenders: ben, deedouble add:3 square
1
-225
1