Callback Functions

Published: Monday, May 23, 2022

Greetings, friends! Have you ever been asked what a "callback function" is during an interview? It's actually really simple! You may have been using callback functions without even knowing what they were called, no pun intended.

A callback function is a function passed into another function as a parameter. Let's look at an example.

javascript
Copied! ⭐️
function addTwoNumbers(num1, num2) {
  return num1 + num2;
}

function multiplyTwoNumbers(num1, num2) {
  return num1 * num2;
}

function outputCalculation(callback, num1, num2) {
  const result = callback(num1, num2);
  console.log(result);
}

outputCalculation(addTwoNumbers, 2, 5); // OUTPUT: 7
outputCalculation(multiplyTwoNumbers, 2, 5); // OUTPUT: 10

In the example above, we are creating a function called outputCalculation that accepts 3 parameters: a callback and two numbers. We are calling this function twice. The first time we call it, we pass in the addTwoNumbers function, which gets executed inside the outputCalculation function. Then, we save the result and log it to the console. We then call outputCalculation again and pass in the multiplyTwoNumbers function as a callback.

tip
Sometimes, you may hear people just say "callbacks" instead of "callback functions." They're usually talking about the same thing.

Notice how powerful callback functions can be. We can write one function, outputCalculation to log information to the console, but it can accept multiple types of functions. In our example, we can pass in a function to add two numbers or multiply two numbers. The operation we perform can change based on the function we pass in! This example may seem silly, but when you deal with more complex functions, this pattern will really come in handy!

In JavaScript, functions are known as First-class functions. This means that we can treat functions like other types of variables such as numbers and strings. We can assign a function to a variable, pass a function into another function, and we can even return functions from within another function! In other programming languages, it may not be possible or as straightforward to pass functions as a parameter to another function.

Callback functions are used heavily in JavaScript, so it's important to understand how they work. Next time you're asked about callback functions, I'm sure you'll be ready 🙂.

Resources