A higher-order function takes a function as an argument or returns one. It is the core of functional-style JavaScript.
Taking a function
function repeat(n, action) {
for (let i = 0; i < n; i++) action(i);
}
repeat(3, (i) => console.log("tick", i));
const applyAll = (value, ...fns) => fns.map((f) => f(value));
console.log(applyAll(9, Math.sqrt, (x) => x * 2, String));tick 0
tick 1
tick 2
[ 3, 18, '9' ]Returning a function
const greaterThan = (n) => (m) => m > n;
const isAdult = greaterThan(17);
console.log([12, 18, 30].filter(isAdult));
function logged(fn) {
return function (...args) {
const result = fn.apply(this, args);
console.log(`${fn.name}(${args.join(", ")}) = ${result}`);
return result;
};
}
const add = logged(function add(a, b) { return a + b; });
add(2, 3);[ 18, 30 ]
add(2, 3) = 5Synchronous vs asynchronous callbacks
console.log("start");
[1, 2].forEach((n) => console.log("sync callback", n)); // runs now
setTimeout(() => console.log("async callback"), 0); // runs later
console.log("end");start
sync callback 1
sync callback 2
end
async callbackThe parseInt trap
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]What is a callback function?