CodeBlanks Logo Icon CodeBlanks

Callback functions

JavaScript course · Intermediate · Lesson 66/134

Learn the idea of a callback passed as a function argument.

Callback functions

In JavaScript, functions are values; so you can pass a function as an argument to another function. A function passed this way is called a callback, because the outer function calls it back at the right time.

function greet(name, callback) {
  callback(name);
}

This pattern is called a higher-order function: the outer function accepts a parameter that is itself a function. You have already seen addEventListener('click', handler) and setTimeout(fn, 1000); both take callbacks.

Pass by name or inline

You can pass a callback in two ways: by name, or as an inline arrow function. When passing by name, do not use parentheses; greet(name, hello) is correct, while greet(name, hello()) calls hello right away and passes its result.

function hello(name) {
  console.log('Hello ' + name);
}
greet('Alex', hello);

You can also write it inline with an arrow function: greet('Alex', (n) => console.log(n)). Both ways work; passing by name improves readability for larger functions.

Exercise Write the greetUser function

Define a function named greetUser. It should take two parameters: name and callback. Inside the function, create a const message variable holding a greeting text that includes the name. Then call callback(message).

Show example solution
function greetUser(name, callback) {
  const message = `Hello, ` + name;
  callback(message);
}

Test yourself

  1. Which one is a higher-order function?

    // A
    function add(a, b) { return a + b; }
    // B
    function run(fn) { fn(); }
    // C
    function greet() { console.log('hi'); }
    // D
    const x = 5;
    • A
    • B
    • C
    • D
    Show answer

    B — Correct! run takes a function parameter, so it is a higher-order function.

  2. Add the callback parameter

    function greet(name, ____) {
      callback(name);
    }
    Show answer
    function greet(name, callback) {
      callback(name);
    }
  3. Match the concepts

    callback
    Function called later
    higher-order function
    Takes a function parameter
    greet(name, hello)
    Pass by name
    greet(name, hello())
    Call immediately
  4. What happens if you write addEventListener('click', handleClick())?

    • An error is thrown
    • handleClick runs when the event fires
    • Nothing happens
    • handleClick is called immediately, the event is not waited for
    Show answer

    handleClick is called immediately, the event is not waited for — Correct! The parentheses call handleClick right away; its return value (undefined) is registered as the listener.

All lessons in Intermediate