Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Callbacks

Since a function is a value, it can be passed into another function as an argument. A function passed in to be called later is known as a callback. Callbacks are everywhere: in array methods, click handlers and timers.

Passing a function

A function is passed by name, without parentheses. Inside the receiving function it is called through the parameter, like any function:

function sayHello() {
  console.log('Hello!'); // Hello!
}
 
function run(callback) {
  callback();
}
 
run(sayHello);

The run function does not know what the callback does — it simply calls whatever it was given.

A callback with arguments

The receiving function can pass data to the callback. That way one function decides when to act, and the callback decides what to do:

function repeat(times, action) {
  for (let i = 1; i <= times; i++) {
    action(i);
  }
}
 
repeat(3, (n) => console.log(`Repeat ${n}`));
// Repeat 1
// Repeat 2
// Repeat 3

An arrow function in place

A callback does not have to be declared in advance. Most often it is written right in the call as a short arrow function, as in the example above. A separate name is only needed when the callback is long or used in several places.

function calculate(a, b, operation) {
  return operation(a, b);
}
 
console.log(calculate(6, 3, (x, y) => x + y)); // 9
console.log(calculate(6, 3, (x, y) => x * y)); // 18

One calculate function performs different actions depending on the callback.

Callbacks in array methods

Built-in array methods take a callback and call it for every element. For example, map() builds a new array from the callback's results, and filter() keeps the elements for which the callback returned true:

const prices = [10, 25, 40];
 
console.log(prices.map((p) => p * 2).join(', '));     // 20, 50, 80
console.log(prices.filter((p) => p > 20).join(', ')); // 25, 40

These methods are covered in detail in the arrays chapter.

Callbacks and time

A callback lets you postpone an action: the function calls it not right away but when something happens — time passes, the user clicks a button or data arrives from a server. For example, setTimeout(callback, 1000) calls the callback after one second. Timers and events are covered in the chapters on asynchronous code and the DOM.

Common mistake

If you put parentheses after the callback's name, the function runs immediately, and the receiving function gets its result instead of the function itself:

function getGreeting() {
  return 'Hello!';
}
 
function run(callback) {
  return typeof callback;
}
 
console.log(run(getGreeting));   // function
console.log(run(getGreeting())); // string

Pass the function without parentheses: run(getGreeting). The function that receives it will do the calling.

Thanks for reading!

Donate to the site — we work hard for you.