Pass functions as callbacks
Quick answer
A callback is a function supplied to another operation so that the receiving code can invoke it. A callback may execute immediately or later depending on the receiving API.
How it works
A higher-order function receives a function or returns one. Pass the function value without parentheses when the receiver is meant to choose when to call it. Define the expected callback arguments and return value.
function applyTo(n, operation) { return operation(n); }console.log(applyTo(6, n => n + 1));Expected output in Node.js:
7applyTo calls the supplied function with 6.
function twice(n, action) { return action(action(n)); }console.log(twice(3, n => n * 2));Expected output in Node.js:
12The same behavior is applied two times.
Common mistakes
Callbacks are not inherently asynchronous. Passing operation() sends its result, not the function.
Practice
Make an apply function that can square or negate a number.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pass functions as callbacks — Knowledge Check
Apply the taught concept and reason about the result.
What is a callback?
Given function apply(n,f){return f(n);} what is apply(4,n=>n*3)?
Which expression passes an existing function f without invoking it to run?
Does every callback execute asynchronously?
What makes a function higher-order?