Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 25 of 58

Callbacks and functions as values

Learn that functions are values you can store and pass around, how callbacks work, and how to write higher-order functions that take or return functions.

11 minFunctionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonPass a function to another function as a callback, write your own function that accepts one, and read common patterns such as forEach and setTimeout.

After this lesson you can pass a function into another function, and you will recognise callbacks in code written by others. This is one of the most important ideas in JavaScript, because so much of the language, from clicks to timers to array methods, is built on it.

Functions are values

In the Functions lesson you saw that a function can be assigned to a variable. This is true everywhere. A function is a value, like a number or a string:

javascript
function shout(text) {
  return text.toUpperCase() + "!";
}

const fn = shout;                // no parentheses: copying the function itself
console.log(fn("hello"));        // HELLO!

const tools = [shout, Math.round];
console.log(tools[0]("hey"));    // HEY!
console.log(tools[1](4.6));      // 5

The key difference to remember: shout is the function; shout("hi") is the result of running it.

Passing a function as an argument

If a function is a value, you can hand it to another function. Look at this:

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

repeat(3, function (index) {
  console.log("Run number " + index);
});
// Run number 0
// Run number 1
// Run number 2

repeat does not know what the action is. It only knows to call it, once per loop pass, handing it the index. The function you passed, action, is a callback: you give it to somebody else, who calls it back when appropriate.

The same code with an arrow function and a named function:

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  function show(text) {
    out.textContent += text + "\n";
  }

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

  repeat(2, index => show("Arrow callback, index " + index));

  function announce(index) {
    show("Named callback, index " + index);
  }
  repeat(2, announce); // pass the name only, no parentheses
</script>

The second call passes announce itself. Writing announce(...) with parentheses there would run it immediately, which is a mistake covered below.

Callbacks you already use

Callbacks are everywhere in JavaScript:

javascript
// Array methods
[10, 20, 30].forEach(number => console.log(number * 2));
// 20
// 40
// 60

const words = ["apple", "fig", "banana"];
console.log(words.filter(word => word.length > 3)); // [ 'apple', 'banana' ]

// Timers
setTimeout(() => console.log("one second later"), 1000);

In a browser page you also pass a callback to addEventListener("click", handler), so the browser can call your function when a click happens. Later lessons on events and timers use this constantly.

Writing a function that takes a callback

Callbacks make a function flexible. Here, applyToAll handles the looping, and the caller decides what to do to each item:

javascript
function applyToAll(list, transform) {
  const result = [];
  for (const item of list) {
    result.push(transform(item));
  }
  return result;
}

console.log(applyToAll([1, 2, 3], n => n * 10));       // [ 10, 20, 30 ]
console.log(applyToAll(["a", "b"], s => s.toUpperCase())); // [ 'A', 'B' ]

This is essentially what the built-in map method does. You wrote a version of it yourself.

Higher-order functions

A function that takes a function, or returns one, is called a higher-order function. You have seen both kinds:

javascript
// Takes a function
function twice(fn, value) {
  return fn(fn(value));
}
console.log(twice(n => n + 3, 10)); // 16

// Returns a function
function adder(amount) {
  return n => n + amount;
}
const addFive = adder(5);
console.log(addFive(1)); // 6

The second example uses a closure, which you met in the Closures lesson.

Synchronous and asynchronous callbacks

Not all callbacks run immediately. forEach and map are synchronous: they call your function right away, during the call. setTimeout and event handlers are asynchronous: your function runs later, after other code has finished.

javascript
console.log("start");
setTimeout(() => console.log("timer"), 0);
console.log("end");
// start
// end
// timer

Even with a delay of 0, the callback waits until the current code is done. The timers and event loop lesson explains why.

Choosing between a named function and an inline one

You can pass a callback in two ways. An inline arrow is best when the logic is one or two lines and used once. A named function is better when the logic is longer, is reused, or deserves a descriptive name that explains the intent:

javascript
const ages = [12, 34, 17, 60];

function isAdult(age) {
  return age >= 18;
}

console.log(ages.filter(isAdult)); // [ 34, 60 ]
console.log(ages.filter(age => age > 50)); // [ 60 ]

Notice how ages.filter(isAdult) reads almost like a sentence. A good name often removes the need for a comment.

Why callbacks are useful

The big benefit is separation of concerns. The function that takes the callback handles the part that stays the same, such as looping, waiting or listening. The callback holds the part that changes. A timer does not care what your code does when the time is up; it only knows when to call you. That split lets one tool serve thousands of different programs, and it is the reason JavaScript, which has only one main thread, can stay responsive while it waits for clicks and network replies.

Common mistakes

Calling the function instead of passing it. setTimeout(sayHi(), 1000) runs sayHi now and passes its result. Write setTimeout(sayHi, 1000). To pass an argument, wrap it: setTimeout(() => sayHi("Asha"), 1000).

Forgetting what the callback receives. Array methods call your callback with the item, the index and the whole array. A function that expects other arguments can misbehave: ["1", "2", "3"].map(parseInt) gives [1, NaN, NaN], because parseInt treats the index as a number base. When in doubt, wrap it: .map(text => parseInt(text, 10)).

Expecting a return value from forEach. forEach returns undefined. Use map to build a new array.

Assuming the callback runs at once. Timer and event callbacks run later, so code after them runs first.

Deeply nested callbacks. Callbacks inside callbacks inside callbacks become hard to read. Promises and async and await, covered later, solve this.

Exercise

Write a function countMatches(list, test) that returns how many items make the callback test return true. Use it to count the even numbers in [1, 2, 3, 4, 5, 6] and the words longer than 4 letters in ["tree", "plant", "forest"]. Then write makeTester(min) that returns a function checking whether a number is at least min, and pass its result as the callback.

Next: Rest and spread.

Key points

  • In JavaScript a function is a value, so you can store it in a variable, put it in an array, or pass it as an argument.
  • A callback is a function you give to another function to be called later or at the right moment.
  • A function that takes or returns another function is called a higher-order function.
  • Pass the function itself, not the result of calling it: write run(task), not run(task()).
  • Callbacks are the foundation of array methods, event handlers and timers.

Check yourself

1. What is a callback?
2. What is the problem with setTimeout(sayHi(), 1000)?
3. What makes a function a higher-order function?
4. Which call passes a callback to forEach?