Skip to content
  • Higher-Order Functions & Callbacks · JavaScript

Higher-Order Functions & Callbacks

LearnViaNotes @learnvianotes· 1 min read

A higher-order function takes a function as an argument or returns one. It is the core of functional-style JavaScript.

Taking a function

JavaScript
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));
Output
tick 0
tick 1
tick 2
[ 3, 18, '9' ]

Returning a function

JavaScript
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);
Output
[ 18, 30 ]
add(2, 3) = 5

Synchronous vs asynchronous callbacks

JavaScript
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");
Output
start
sync callback 1
sync callback 2
end
async callback

The parseInt trap

JavaScript
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map(Number));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
Output
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

What is a callback function?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report