Skip to content
FunctionsChapter 19 / 47Intermediate4 min read

Higher-Order Functions

Learn JavaScript higher-order functions and callbacks, including passing functions as arguments, returning functions, and patterns like map and filter.

On this page

1. What are higher-order functions?

In JavaScript, functions are "first-class values". You can store them in variables, pass them as arguments, and return them from other functions. A function passed as an argument is called a callback.

map, filter, setTimeout, and addEventListener are all higher-order functions that you use every day.

2. Why does it matter?

A lot of tasks share the same structure, and only one step in the middle changes. Higher-order functions pull that changing step out.

A separate loop for every taskWith a higher-order function
A new for loop for every filterOne filter, the condition lives in a callback
The same loop logic in 10 placesLoop logic in one place, the task in a callback
What is happening is hidden inside the loopThe function name tells you what it does
Hard to reuseSmall callbacks you can mix and reuse

3. Where is it used?

AreaExample
Arraysmap, filter, reduce, find, some, toSorted
EventsaddEventListener("click", handler)
TimerssetTimeout(callback, 1000)
Asyncpromise.then(callback)
Utilitiesdebounce(fn, 300), once(fn), memoize(fn)
ReactRendering a list with items.map((item) => ...)

4. How does it work?

A higher-order function works in two ways:

WayWhat happensExample
Takes a functionAsks a callback for part of the workarr.filter(isActive)
Returns a functionRemembers a setting and builds a new functionmakeMultiplier(2)
Callback flow
Give the higher-order function data and a callback
It does its fixed work (like looping)
It calls the callback at each step
It uses the callback's answer to build the result

Higher-order functions that return a function rely on Closures, because the new function remembers the settings from outside.

5. Code example

Passing a function as an argument

js
function repeat(times, action) {
  for (let i = 0; i < times; i++) {
    action(i);
  }
}

repeat(3, (i) => console.log(`Step ${i + 1}`));

const isAdult = (user) => user.age >= 18;
const users = [
  { name: "Ali", age: 22 },
  { name: "Hina", age: 15 },
];
console.log(users.filter(isAdult).map((u) => u.name));

Returning a function

js
function once(fn) {
  let called = false;
  let result;
  return (...args) => {
    if (!called) {
      called = true;
      result = fn(...args);
    }
    return result;
  };
}

const initApp = once(() => {
  console.log("App initialized");
  return "ready";
});

console.log(initApp());
console.log(initApp());

How does the code work?

PartMeaning
repeat(3, ...)repeat owns the loop, the callback owns the task
isAdultA named callback that can be reused
filter(isAdult).map(...)A chain of two higher-order functions, gives ["Ali"]
once(fn)Takes fn and returns a new function
called and resultRemembered through a closure
Second initApp()The message is not printed again, you only get ready

Interview tip

There are two kinds of callbacks: synchronous (like map, runs immediately) and asynchronous (like setTimeout, runs later). Be sure to mention this difference in an interview.

6. Common mistakes

Mistake: Passing the result of a function instead of the callback

Why? In setTimeout(showToast(), 1000), showToast runs immediately and setTimeout receives undefined.

Better: Pass a function reference or an arrow function: setTimeout(showToast, 1000) or setTimeout(() => showToast(msg), 1000).

Mistake: Forgetting the extra arguments that map passes

Why? map gives the callback (value, index, array). ['1','2','3'].map(parseInt) gives a wrong result because the index becomes the radix.

Better: Write an explicit arrow: arr.map((s) => parseInt(s, 10)) or arr.map(Number).

Mistake: Forgetting return in a callback

Why? In an arrow function with a block body, if there is no return, filter and map get undefined.

Better: If it is a single expression, remove the braces. Otherwise write return yourself.

7. What to learn before and after

Suggested order
Closures
Higher-Order Functions
Array Methods
Callbacks
Promises

Final quick revision

PointDetail
Higher-order functionTakes or returns a function
CallbackA function passed as an argument
First-class functionsFunctions are treated like values
Sync vs async callbackRuns immediately vs runs later
Returning a functionA closure remembers the settings