Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 156 ยท Functions

Higher-Order Functions and Callbacks

Treat JavaScript functions as values - store them, pass them as callbacks, return them from other functions and build reusable helpers like compose.

In JavaScript, functions are values. You can store a function in a variable, put it in an array or object, pass it to another function, and return it from a function โ€” exactly like a number or a string. Languages that work this way are said to have first-class functions.

A function that takes another function as an argument, or returns one, is called a higher-order function. The function you pass in is called a callback, because the higher-order function will "call it back" at the right moment. This pattern is everywhere: array methods like map() and filter(), timers, event listeners and promises all take callbacks. Once you are comfortable with it, you can write your own reusable tools too.

Functions are values

A function name without parentheses refers to the function itself. Adding () calls it and gives you its return value. Keep that difference in mind โ€” it explains most callback bugs.

JS Functions stored like any other value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The transforms object maps names to functions. Looking up a function by name and calling it is a tidy alternative to a long if/else if chain or a switch.

Callbacks: passing a function in

A callback lets the caller decide what happens while the higher-order function decides when or how often. Here is a small one you can read from top to bottom:

JS Writing your own higher-order functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

countWhere knows how to loop and count; the callback knows what to look for. You wrote the loop once and reused it for three different questions. Notice that isEven is passed without parentheses: you hand over the function, and countWhere calls it.

Built-in higher-order functions

The language and the browser are full of functions that take callbacks:

  • Array methods: map(), filter(), reduce(), forEach(), find(), some(), every() and sort() all take callbacks. They get their own lesson, map, filter, reduce and forEach.
  • Timers: setTimeout(callback, ms) runs a callback later. See setTimeout and setInterval.
  • Events: button.addEventListener("click", callback) runs a callback every time the button is clicked. See Events.
  • Promises: promise.then(callback) runs a callback when an asynchronous result arrives. See Promises.
JS Callbacks in built-in methods

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The timer's callback runs after everything else, even though its line comes earlier. The asynchronous JavaScript chapter explains why.

Pass the function, don't call it

The most common callback mistake is adding parentheses:

JavaScript
function ring() {
  console.log("Ring!");
}

setTimeout(ring, 1000);     // correct: pass the function
setTimeout(ring(), 1000);   // wrong: calls ring now, passes its result (undefined)

If you need to pass arguments, wrap the call in a small arrow function: setTimeout(() => ring("loud"), 1000).

Mind the extra arguments

Higher-order functions often call your callback with more arguments than you expect. map() passes the element, its index and the whole array. That usually doesn't matter, but it can surprise you when the callback is a function with an optional second parameter:

JS The parseInt surprise

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line calls parseInt("10", 0), parseInt("10", 1) and parseInt("10", 2), giving 10, NaN and 2. When in doubt, wrap the callback in an arrow that passes exactly the arguments you mean.

Returning functions

A higher-order function can also produce functions. Thanks to closures, the returned function remembers the arguments that were used to create it:

JavaScript
function multiplier(factor) {
  return (n) => n * factor;
}

const double = multiplier(2);
const triple = multiplier(3);

double(8); // 16
triple(8); // 24

Wrapping a function

A powerful use of returned functions is a wrapper: take a function, return a new function that does something extra and then calls the original. This adds behavior without editing the original code.

JS A logging wrapper and compose

Press Run (or Ctrl + Enter) to see the console output here.

No output.

withLogging works with any function, because it just forwards whatever arguments it receives using rest and spread syntax. pipe builds one function out of several small ones, feeding the output of each into the next. Small functions that do one thing, combined with higher-order helpers, are the heart of a style called functional programming.

Built-in helpers exist too. You rarely need to write once, debounce or pipe by hand in big projects โ€” utility libraries provide them. But writing them yourself once is the best way to understand callbacks and closures, and the Timers lesson builds a debounce from scratch.

Why bother?

Higher-order functions let you separate what you want from how it is done. Compare a hand-written loop that collects the names of active users with users.filter((u) => u.active).map((u) => u.name). The loop version mixes a counter, an empty array, an if and a push with the actual question. The higher-order version reads almost like the sentence "the names of the active users".

They also cut repetition. Once a loop, a retry, a timing measurement or a logging step lives in one higher-order function, every caller gets it for free, and fixing a bug in it fixes it everywhere.

Keep callbacks small and give them names when they grow. An inline arrow is perfect for price => price * 2. A ten-line callback is easier to read and test as a named function, function isOverdue(invoice) { โ€ฆ }, passed by name: invoices.filter(isOverdue).

Callbacks and this

When you pass an object's method as a callback, it is called as a plain function, not as a method. If the method uses this, it may no longer point at the object:

JavaScript
const counter = {
  count: 0,
  increment() { this.count++; },
};

setTimeout(counter.increment, 100);        // this is not counter
setTimeout(() => counter.increment(), 100); // fine: called as a method

Wrapping the call in an arrow is the usual fix. The full story is in The this Keyword and call, apply and bind.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a function "higher-order"?

    Higher-order functions work with other functions as values, either receiving them as callbacks or returning them.
  2. 2. Which line runs notify after one second?

    Pass the function itself. notify() would call it immediately and pass its return value to setTimeout.
  3. 3. What does ["10", "10", "10"].map(parseInt) return?

    map passes the index as the second argument, which parseInt treats as the radix: 0 (auto), 1 (invalid) and 2 (binary).
  4. 4. Given const add = (a) => (b) => a + b;, what is add(2)(5)?

    add(2) returns a function that remembers a = 2. Calling it with 5 returns 2 + 5.

Summary

  • Functions are values: you can store them, put them in objects and arrays, pass them and return them.
  • A higher-order function takes or returns a function; the function you pass in is a callback.
  • Pass callbacks without parentheses; wrap the call in an arrow when you need to supply arguments.
  • Built-ins like map(), filter(), setTimeout() and addEventListener() all take callbacks, sometimes with extra arguments.
  • Returned functions use closures to remember their settings; wrappers like withLogging and pipe add or combine behavior without changing the original code.

Next: Recursion โ€” functions that call themselves to solve problems step by step.