JavaScript Callbacks and Higher-Order Functions with Examples

In JavaScript you can hand a function to another function and say “call this when you need to”. That passed-in function is a callback, and the function that accepts or returns functions is a higher-order function. Array methods, timers, event listeners, Playwright’s test() and page.on() all work this way. In this lesson you will learn to write and use callbacks, build your own higher-order functions, compose small functions into pipelines, and wrap functions with logging and timing for test diagnostics.

Advertisement

📖 What You’ll Learn: callbacks, synchronous versus asynchronous callbacks, higher-order functions that take functions, higher-order functions that return functions, built-in higher-order methods (map, filter, find, sort, reduce), passing named functions versus inline arrows, function composition and pipelines, wrapper functions for logging and timing, and callback pitfalls.


📞 What Is a Callback?

Definition: a callback is a function passed as an argument to another function, which calls it (“calls it back”) at the right moment.

📄 callback.js

function processOrder(orderId, onDone) {
  console.log(`processing order ${orderId}...`);
  const status = "shipped";
  onDone(orderId, status);      // call the callback when the work is finished
}

function notify(id, status) {
  console.log(`order ${id} is ${status}`);
}

processOrder(101, notify);                                // pass a named function
processOrder(102, (id) => console.log(`log: ${id} done`)); // or an inline arrow

⌨️ Terminal

node callback.js

🖥️ Output

processing order 101...
order 101 is shipped
processing order 102...
log: 102 done

⚠️ Watch out: Pass the function, do not call it. processOrder(101, notify) passes the function; processOrder(101, notify()) calls notify immediately and passes its return value (undefined), which then fails with “onDone is not a function”.


⏱️ Synchronous vs Asynchronous Callbacks

A synchronous callback runs right away, before the outer function returns (array methods). An asynchronous callback runs later, after some event or delay (timers, events, network responses).

📄 sync-async.js

console.log("1. start");

[10, 20].forEach((n) => console.log(`2. sync callback: ${n}`));

setTimeout(() => console.log("5. async callback after 0 ms"), 0);

process.nextTick(() => console.log("4. nextTick callback"));

console.log("3. end of script");

⌨️ Terminal

node sync-async.js

🖥️ Output

1. start
2. sync callback: 10
2. sync callback: 20
3. end of script
4. nextTick callback
5. async callback after 0 ms

Even with a 0 ms delay, the timer callback runs only after the current code finishes. Module 10 explains the event loop that decides this order; for now, remember that an async callback never runs in the middle of your current code.


🔼 Higher-Order Functions

Definition: a higher-order function is a function that does at least one of these: takes a function as an argument, or returns a function. Ordinary functions that only work with numbers, strings and objects are called first-order functions.

Taking a function as an argument

📄 takes-function.js

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

repeat(3, (n) => console.log(`run ${n}`));

function measure(label, fn) {
  const start = performance.now();
  const result = fn();
  const ms = (performance.now() - start).toFixed(1);
  console.log(`${label} took ${ms < 50 ? "under 50" : ms} ms`);
  return result;
}

const total = measure("sum to 100000", () => {
  let s = 0;
  for (let i = 1; i <= 100000; i++) s += i;
  return s;
});
console.log(total);

⌨️ Terminal

node takes-function.js

🖥️ Output

run 1
run 2
run 3
sum to 100000 took under 50 ms
5000050000
Advertisement

Returning a function

📄 returns-function.js

function greaterThan(limit) {
  return (value) => value > limit;
}

const slowerThan1s = greaterThan(1000);
console.log([450, 1200, 980, 3100].filter(slowerThan1s));

⌨️ Terminal

node returns-function.js

🖥️ Output

[ 1200, 3100 ]

Functions that return functions rely on closures (see the Closures lesson): slowerThan1s remembers limit.


🧰 Built-in Higher-Order Array Methods

The array methods you will use most are higher-order functions. Each takes a callback that receives (item, index, array):

MethodCallback returnsResult
mapA new valueA new array of the same length
filtertrue/falseA new array with the items that passed
findtrue/falseThe first matching item or undefined
some / everytrue/falseA boolean
sortA negative, zero or positive numberThe same array, sorted in place
reduceThe new accumulatorOne combined value
forEachNothingundefined (side effects only)

📄 array-hofs.js

const tests = [
  { name: "login", ms: 820, tags: ["smoke"] },
  { name: "export", ms: 4300, tags: ["slow"] },
  { name: "search", ms: 1430, tags: ["smoke", "api"] },
];

console.log(tests.map((t) => t.name));
console.log(tests.filter((t) => t.tags.includes("smoke")).map((t) => t.name));
console.log(tests.find((t) => t.ms > 4000)?.name);
console.log(tests.every((t) => t.ms < 5000));
console.log([...tests].sort((a, b) => b.ms - a.ms).map((t) => `${t.name}:${t.ms}`));
console.log(tests.reduce((sum, t) => sum + t.ms, 0));

⌨️ Terminal

node array-hofs.js

🖥️ Output

[ 'login', 'export', 'search' ]
[ 'login', 'search' ]
export
true
[ 'export:4300', 'search:1430', 'login:820' ]
6550

Module 6 covers map, filter and reduce in full depth.


🏷️ Named Functions vs Inline Arrows

You can pass an inline arrow or a named function. Named functions are reusable, testable on their own, and make chains read like sentences:

📄 named.js

const isFailed = (r) => r.status === "failed";
const toName = (r) => r.test;
const byName = (a, b) => a.localeCompare(b);

const results = [
  { test: "search", status: "failed" },
  { test: "cart", status: "passed" },
  { test: "auth", status: "failed" },
];

const failedNames = results.filter(isFailed).map(toName).sort(byName);
console.log(failedNames);

⌨️ Terminal

node named.js

🖥️ Output

[ 'auth', 'search' ]

⚠️ Watch out: Be careful passing existing functions that accept extra parameters. ["1", "2", "3"].map(parseInt) calls parseInt("2", 1) and parseInt("3", 2), because map passes the index as the second argument.

📄 parseint-trap.js

console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
console.log(["1", "2", "3"].map(Number));

⌨️ Terminal

node parseint-trap.js

🖥️ Output

[ 1, NaN, NaN ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]

Advertisement

🔗 Function Composition and Pipelines

Definition: composition combines small functions so the output of one becomes the input of the next. A pipe helper applies functions left to right:

📄 pipe.js

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

const trim = (s) => s.trim();
const collapseSpaces = (s) => s.replace(/\s+/g, " ");
const lower = (s) => s.toLowerCase();

const normaliseText = pipe(trim, collapseSpaces, lower);

console.log(JSON.stringify(normaliseText("   Welcome   BACK,\n  Asha  ")));
console.log(normaliseText("  Order   CONFIRMED ") === "order confirmed");

⌨️ Terminal

node pipe.js

🖥️ Output

"welcome back, asha"
true

normaliseText is a reusable function built from three tiny ones. Text normalisation like this is exactly what you need before comparing UI text in tests.


🎁 Wrapper Functions: Logging, Timing and Error Context

A higher-order function can wrap another function to add behaviour before and after it, without changing the original code. This is sometimes called a decorator.

📄 wrapper.js

function withLogging(name, fn) {
  return (...args) => {
    console.log(`→ ${name}(${args.map((a) => JSON.stringify(a)).join(", ")})`);
    try {
      const result = fn(...args);
      console.log(`← ${name} returned ${JSON.stringify(result)}`);
      return result;
    } catch (e) {
      console.log(`✖ ${name} threw: ${e.message}`);
      throw e;
    }
  };
}

const applyDiscount = withLogging("applyDiscount", (price, code) => {
  if (code !== "SAVE10") throw new Error(`Invalid code ${code}`);
  return price * 0.9;
});

applyDiscount(200, "SAVE10");
try {
  applyDiscount(200, "FREE");
} catch {}

⌨️ Terminal

node wrapper.js

🖥️ Output

→ applyDiscount(200, "SAVE10")
← applyDiscount returned 180
→ applyDiscount(200, "FREE")
✖ applyDiscount threw: Invalid code FREE

Test frameworks use the same idea: Playwright’s test.step("name", async () => {...}) wraps your function so the report shows each step with its duration and result.


🧪 Tester Scenario: A Mini Test Runner

A test runner is a higher-order program: you register callbacks, and it decides when to call them. This 25-line version shows how test(), hooks and reporting work under the hood:

📄 mini-runner.js

const registry = [];
const hooks = { beforeEach: [] };

const test = (name, fn) => registry.push({ name, fn });
const beforeEach = (fn) => hooks.beforeEach.push(fn);

function run() {
  let passed = 0;
  for (const { name, fn } of registry) {
    const context = {};
    try {
      hooks.beforeEach.forEach((hook) => hook(context));
      fn(context);
      passed++;
      console.log(`  ✓ ${name}`);
    } catch (e) {
      console.log(`  ✗ ${name}: ${e.message}`);
    }
  }
  console.log(`${passed}/${registry.length} passed`);
}

// --- tests ---
beforeEach((ctx) => { ctx.cart = []; });

test("cart starts empty", (ctx) => {
  if (ctx.cart.length !== 0) throw new Error("cart not empty");
});
test("adds an item", (ctx) => {
  ctx.cart.push("pen");
  if (ctx.cart.length !== 1) throw new Error("expected 1 item");
});
test("total is calculated", () => {
  const total = [10, 20].reduce((a, b) => a + b, 0);
  if (total !== 40) throw new Error(`expected 40, got ${total}`);
});

run();

⌨️ Terminal

node mini-runner.js

🖥️ Output

  ✓ cart starts empty
  ✓ adds an item
  ✗ total is calculated: expected 40, got 30
2/3 passed
  • test and beforeEach are higher-order functions: they store your callbacks for later.
  • run calls each callback with a fresh context object, which is how fixtures give each test isolated state.
  • A test fails when its callback throws, exactly as in Playwright and Jest.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write applyToAll(numbers, fn) that returns a new array with fn applied to each number (without using map). Test it with a squaring callback.

Show answer

📄 practice1.js

function applyToAll(numbers, fn) {
  const result = [];
  for (const n of numbers) result.push(fn(n));
  return result;
}
console.log(applyToAll([1, 2, 3, 4], (n) => n * n));

🖥️ Output

[ 1, 4, 9, 16 ]

Q2. Write makeLogger(prefix) that returns a function which logs messages with that prefix. Create info and error loggers.

Show answer

📄 practice2.js

const makeLogger = (prefix) => (message) => console.log(`[${prefix}] ${message}`);
const info = makeLogger("INFO");
const error = makeLogger("ERROR");
info("suite started");
error("login failed");

🖥️ Output

[INFO] suite started
[ERROR] login failed

Q3. From [{ name: "a", price: 30 }, { name: "b", price: 120 }, { name: "c", price: 75 }], get the names of items costing more than 50, sorted by price from high to low.

Show answer

📄 practice3.js

const items = [{ name: "a", price: 30 }, { name: "b", price: 120 }, { name: "c", price: 75 }];
const result = items
  .filter((i) => i.price > 50)
  .sort((x, y) => y.price - x.price)
  .map((i) => i.name);
console.log(result);

🖥️ Output

[ 'b', 'c' ]

Q4. Write compose2(f, g) that returns a function computing f(g(x)). Use it to build shout from toUpper and addExclamation.

Show answer

📄 practice4.js

const compose2 = (f, g) => (x) => f(g(x));
const toUpper = (s) => s.toUpperCase();
const addExclamation = (s) => s + "!";
const shout = compose2(addExclamation, toUpper);
console.log(shout("test passed"));

🖥️ Output

TEST PASSED!

Q5. Write timed(fn) that returns a wrapped function which prints how many calls have been made so far each time it is called, then returns the original result.

Show answer

📄 practice5.js

function timed(fn) {
  let calls = 0;
  return (...args) => {
    calls++;
    console.log(`call #${calls}`);
    return fn(...args);
  };
}
const add = timed((a, b) => a + b);
console.log(add(1, 2));
console.log(add(5, 5));

🖥️ Output

call #1
3
call #2
10

Q6. Why does ["10", "10", "10"].map(parseInt) not return [10, 10, 10]? Print the result and a correct version.

Show answer

📄 practice6.js

console.log(["10", "10", "10"].map(parseInt));
console.log(["10", "10", "10"].map((s) => parseInt(s, 10)));

🖥️ Output

[ 10, NaN, 2 ]
[ 10, 10, 10 ]

map passes (item, index), so the calls are parseInt("10", 0) (base 10 by default), parseInt("10", 1) (invalid base: NaN) and parseInt("10", 2) (binary: 2).


🧠 MCQ Quiz: Callbacks and Higher-Order Functions

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is a callback?
  2. Which is a higher-order function?
  3. What is wrong with setTimeout(sendReport(), 1000)?
  4. In which order is this printed?
    setTimeout(() => console.log("A"), 0);
    console.log("B");
  5. What does [1, 2, 3].filter((n) => n > 1) return?
  6. Which method changes the original array?
  7. What does pipe(f, g)(x) compute?
  8. What arguments does map pass to its callback?
  9. What is a wrapper (decorator) function?
  10. In a test runner, why is test("name", fn) a higher-order function?

💼 Interview Questions and Answers

Q1. What is the difference between a callback and a higher-order function?

They are two sides of the same relationship. The higher-order function is the one that accepts (or returns) a function, for example array.map or setTimeout. The callback is the function that is passed in, for example (x) => x * 2. A function can be both: a callback that itself takes a callback.

Q2. What is callback hell, and how is it avoided?

When asynchronous steps are chained with nested callbacks (each step inside the previous step’s callback), code drifts right, error handling is repeated at every level, and the flow is hard to follow. It is avoided with named functions, and in modern code with promises and async/await, which flatten the sequence into ordinary-looking statements (Module 10).

Q3. Write a function that retries another function until it returns true or a limit is reached.

📄 until.js

function until(check, { max = 5 } = {}) {
  for (let attempt = 1; attempt <= max; attempt++) {
    if (check(attempt)) return attempt;
  }
  throw new Error(`Condition not met after ${max} attempts`);
}

console.log(until((n) => n === 3));
try { until(() => false, { max: 2 }); } catch (e) { console.log(e.message); }

⌨️ Terminal

node until.js

🖥️ Output

3
Condition not met after 2 attempts

In real tests the check would be asynchronous and include a delay; Playwright offers expect.poll() and expect(...).toPass() for this.

Q4. Why might passing an object method as a callback break it?

When you pass obj.method as a callback, only the function is passed; when the higher-order function calls it, this is no longer obj. Fix it with an arrow wrapper () => obj.method() or obj.method.bind(obj). The next lesson covers this and bind.


Advertisement

❓ Frequently Asked Questions

🤔 Are callbacks always asynchronous?

No. Array method callbacks run synchronously. Timer, event and I/O callbacks run asynchronously.

🤔 What are examples of higher-order functions in JavaScript?

map, filter, reduce, sort, forEach, setTimeout, addEventListener, Promise.then, and in testing test(), describe(), beforeEach().

🤔 Should I pass named functions or inline arrows?

Inline arrows for short, one-off logic; named functions when the logic is reused, needs tests, or makes a chain easier to read.

🤔 What is function composition used for?

Building complex transformations from small, tested functions, for example normalising text, transforming API data or building test-data variations.


🏁 Summary

  • A callback is a function passed to another function; pass the function itself, not its result.
  • Synchronous callbacks run immediately (array methods); asynchronous ones run later (timers, events, I/O).
  • Higher-order functions take functions as arguments or return them; map, filter, sort and reduce are built-in examples.
  • Named callbacks, pipe/compose and wrapper functions keep code small, reusable and testable.
  • Test runners are higher-order programs: they store your test callbacks and call them with fresh context.

Next, continue with Lesson 23: this, call, apply and bind.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in