LearnFrenzy
Sign in Take a free test

Functions, Scope and Closures · Lesson 11 of 40

Higher-Order Functions and Callbacks

5 min read Updated Nov 7, 2026 Saurabh Samir

Because functions are values, a function can take another function as an argument or return one. Such a function is called a higher-order function, and the function you pass in is a callback. You already use them: setTimeout(fn, 1000), button.addEventListener("click", fn) and array.map(fn) are all higher-order functions.

In this lesson

  • Callbacks: passing behaviour into a function
  • Writing your own higher-order functions
  • IIFEs, composition and currying
  • Debounce – a real-world higher-order function

Callbacks

function repeat(times, action) {
  for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (n) => console.log(`Reminder ${n}: submit assignment`));

function processPayment(amount, onSuccess, onFailure) {
  if (amount > 0) onSuccess(`TXN${1000 + amount}`);
  else onFailure("Invalid amount");
}
processPayment(250, (id) => console.log("Success:", id), (err) => console.log("Error:", err));
processPayment(0, (id) => console.log("Success:", id), (err) => console.log("Error:", err));

Output

Reminder 1: submit assignment
Reminder 2: submit assignment
Reminder 3: submit assignment
Success: TXN1250
Error: Invalid amount

Callbacks let the caller decide what happens while the function decides when. In chapter 9 you'll see why deeply nested callbacks for asynchronous work became a problem, and how promises fixed it.

Writing a higher-order function

Here is a simplified version of the built-in filter, showing exactly how array methods use callbacks:

function myFilter(array, test) {
  const result = [];
  for (const item of array) {
    if (test(item)) result.push(item);
  }
  return result;
}
const prices = [120, 899, 45, 1500, 300];
console.log(myFilter(prices, (p) => p < 500));
console.log(prices.filter((p) => p < 500));     // the built-in does the same

Output

[ 120, 45, 300 ]
[ 120, 45, 300 ]

myFilter(prices, test)

  1. For each item120, 899, 45…
  2. Call test(item)your callback decides: keep or not
  3. Collect the kept itemsinto a new array
  4. Return the new arraythe original is untouched

Functions that return functions

function withLogging(fn, name) {
  return (...args) => {
    const result = fn(...args);
    console.log(`${name}(${args.join(", ")}) = ${result}`);
    return result;
  };
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add, "add");
loggedAdd(2, 3);
loggedAdd(10, -4);

Output

add(2, 3) = 5
add(10, -4) = 6

This "wrap a function to add behaviour" pattern is how logging, caching, retries and permission checks are added in real codebases without changing the original function.

IIFE: run a function immediately

const config = (() => {
  const env = "production";
  const apiBase = env === "production" ? "https://api.example.com" : "http://localhost:3000";
  return { env, apiBase };
})();
console.log(config.apiBase);

Output

https://api.example.com

An Immediately Invoked Function Expression creates a private scope and runs once. Before ES modules it was the standard way to avoid polluting the global scope; today it's still handy for computing a value with temporary variables, or for using await in older environments.

Composition and currying

const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);

const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const slugify = (s) => s.replace(/[^a-z0-9]+/g, "-");

const toSlug = pipe(trim, lower, slugify);
console.log(toSlug("  JavaScript Closures Explained! "));

// Currying: a function of many arguments becomes a chain of one-argument functions
const priceWithTax = (rate) => (amount) => Math.round(amount * (1 + rate));
const withGst18 = priceWithTax(0.18);
console.log(withGst18(1000), withGst18(250));

Output

javascript-closures-explained-
1180 295

Notice the trailing dash in the slug – the "!" became "-". Composition makes it easy to fix: add one more step.

const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
const toSlug = pipe(
  (s) => s.trim().toLowerCase(),
  (s) => s.replace(/[^a-z0-9]+/g, "-"),
  (s) => s.replace(/^-|-$/g, "")          // remove leading/trailing dashes
);
console.log(toSlug("  JavaScript Closures Explained! "));

Output

javascript-closures-explained

Debounce: a real higher-order function

A search box shouldn't call the server on every keystroke. debounce returns a wrapped function that only runs after the calls stop for a given delay – it combines a callback, a closure and a timer:

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
const search = debounce((q) => console.log("Searching for:", q), 100);
search("j");
search("ja");
search("jav");
search("java");          // only this one runs, 100 ms after the last call

Output

Searching for: java

Interview angle

"Implement debounce" and "implement throttle" are among the most common JavaScript coding questions. Debounce waits for a pause; throttle runs at most once per interval (useful for scroll and resize handlers).

Practice

Try it yourself

  1. Write myMap(array, fn) that works like array.map, passing the item and its index.

    Show solution
    function myMap(array, fn) {
      const out = [];
      for (let i = 0; i < array.length; i++) out.push(fn(array[i], i));
      return out;
    }
    console.log(myMap(["a", "b"], (ch, i) => `${i}:${ch.toUpperCase()}`));

    Output

    [ '0:A', '1:B' ]

Quick check

What makes a function "higher-order"?

It takes a function as an argument, returns a function, or both.

What is currying?

Turning f(a, b) into f(a)(b) so arguments can be supplied one at a time to create specialised functions.

Debounce vs throttle?

Debounce runs after calls stop for a delay; throttle runs at most once per time interval while calls continue.

Summary

  • A callback is a function passed in; a higher-order function takes or returns functions.
  • Wrapping functions adds behaviour (logging, caching) without changing them.
  • IIFEs, composition, currying and debounce are everyday higher-order patterns.

Interview practice: JavaScript core concepts interview questions and tricky questions on closures and this.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links