Learn JavaScript
❯ functions.callbacks

Callbacks & Higher-Order Functions in JavaScript

$concept

Higher-order functions take or return functions; callbacks are functions passed for later invocation — array methods, timers, and event listeners all run on them. This composition style (small functions combined into pipelines) is idiomatic JavaScript's core idiom.

Callback discipline: consistent signatures (error-first in Node: (err, data)), no uncaught throws across async boundaries, and named functions for non-trivial logic (anonymous nesting pyramids read terribly). Promises and async/await later formalize the async half of this pattern.

$how it works
1

Pass behavior, not just data

[1,2,3].map(double) hands the function itself — map invokes it per element with (value, index, array).

2

Sync vs async callbacks

Array methods call back synchronously (ordered, immediate); timers/events call back later through the event loop.

3

Error-first convention (Node)

fs.readFile(path, (err, data) => ...) — errors arrive as values, not throws, across async boundaries.

4

Name the non-trivial

Inline arrows suit one-liners; multi-step callbacks deserve names for stack traces and reuse.

$example
function applyTwice(f, x) {
return f(f(x));
}
let add3 = n => n + 3;
console.log(applyTwice(add3, 4));
Output
10
1applyTwice receives add3 as a value — functions pass like numbers.
2f(f(4)) applies twice: 4 → 7 → 10.
3Higher-order composition from three lines — behavior parameterized like data.
$use cases
Array transformation pipelines (map/filter/reduce chains)
Event listeners and timer callbacks
Node-style error-first async APIs
Custom utilities (retry, debounce, memoize) wrapping functions

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.