DEV Community

Sana Mohiuddin
Sana Mohiuddin

Posted on

Callback Functions: Do we Need Them?

Before we can dive into the complexity that is a callback function, let us first define what a function is. A function is a set of statements that usually take in data (in the form of parameters) and returns a result. It has to be called in order to for the set of statements to occur.

function hello(name) {
  console.log(`Hello ${name}!`);
}
Enter fullscreen mode Exit fullscreen mode

If you wanted to call the hello function above you would need to write the following code:

hello('Sara');
//log: Hello Sara!
Enter fullscreen mode Exit fullscreen mode

The form of calling a function is the function name and set of parentheses after. Inside those parentheses if there are any parameters associated with the function, you may pass the necessary values as arguments. In the case of the above example, "Sara" is passed to the hello function, which leads to "Hello Sara!" being logged. Now that we know the basics of a function and how to call it, let's look into callback functions.

What is a Callback Function?

A callback function is a function that is passed as an argument, and will be called in the set of statements of the higher-order function. The higher-order function in the code snippet below is createNewNum, as you can see one of the parameters is labeled callback. When createNewNum is called sumNums is passed as an argument. It is called within the higher-order function.

function createNewNum(num1, num2, num3, callback) {
  const newNum = callback(num1, num2, num3);
  console.log(`My number is ${newNum}`);
}

function sumNums(num1, num2, num3) {
    return num1 + num2 + num3;
}

createNewNum(1, 2, 3, sumNums);
//log: My number is 6
Enter fullscreen mode Exit fullscreen mode

This is just one example of the many ways you can use a callback function.

Using Callback while Handling Events

One of the most common ways is JavaScript to utilize a callback function is when you are working with an event listener. Let us imagine we have a button and we want it to log a message to the user when it is clicked.

button.addEventListener('click', handleBtnClick);

function handleBtnClick(event) {
  console.log('I have been clicked');
}
Enter fullscreen mode Exit fullscreen mode

If you take a deeper look at the code above, you may be able to see that handleBtnClick is a callback function. It is an argument passed to the addEventListener function. Once the button that is being "listened" to has been clicked it will call the handleBtnClick function and execute the set of statements within it.

You can begin to see how valuable callbacks can be, and how they can be used in many different places. You may begin to wonder how we are able to pass functions as an argument. That is what we will explore in the next section.

Why are Callback Functions Possible?

The reason we are able to pass functions as an argument is because of the nature of the JavaScript language. In JavaScript, functions are object, specifically they are first-class objects. Objects in JavaScript are a little different than objects in Object-Oriented Languages. Because of this, we can do a lot of different things that other languages do not permit. For example, a function can be assigned to a variable as shown below.

const hello = function(name) {
  console.log(`Hello ${name}!`);
}

hello('Sara');
//log: Hello Sara!
Enter fullscreen mode Exit fullscreen mode

You can also return a function within another function, and of course the reason for this post, you can pass a function as an argument. Now that we are more familiar with what a callback function is, how it works and why they are possible let's look at a few more example of when we might use them.

Using Callback to Iterate Arrays

Iterating over an array is one of the most important skills a developer must be able to do. If you need to find something within the array or manipulate each element of the array, looping through the array will be necessary in doing so. JavaScript provides you with some built-in methods that help you do just that. The most simple is the for...of, which allows you to iterate over each element in the array and do something with that element. However, the methods we will look at are the array iterator methods that use callback functions. These methods are the .find, .filter, .map and .reduce. For the purpose of this post we will take a deeper look at the .filter method and how it uses a callback function to produce the intended result. This particular method will search through the array and return a new array that contains the elements that pass some requirement that is set by the callback function. For example what if we want to find all the elements that are divisible by 2 in an array.

const numArray = [1, 6, 7, 3, 25, 20, 8, 9];

const newArray = numArray.filter(divisbleByTwo);

function divisbleByTwo(num) {
  return num % 2 === 0;
}

console.log(newArray);
//log: [6, 20, 8];
Enter fullscreen mode Exit fullscreen mode

In the code snippet, the argument being passed to the filter array is a function that is called within the filter array to produce the results that are shown. You may also create a function within the parentheses, instead of declaring it separately if you know that you won't need the function in other part of your code. You can even use an arrow function instead of the function declaration. If you are new to JavaScript, there is an example of an arrow function below.

const numArray = [1, 6, 7, 3, 25, 20, 8, 9];

const newArray = numArray.filter((num) => {
  return num % 2 === 0;
});

console.log(newArray);
//log: [6, 20, 8];
Enter fullscreen mode Exit fullscreen mode

This is a much shorter and concise way of doing what was done in the last code block and producing the same result. You can make it even shorter and omit the pair of parenthesis around num because there is only one parameter and bringing the return statement up to the same line. Now you know some cool ways to use callback functions, let's delve deeper onto why they are needed.

Why Use Callback Functions?

Callback functions are necessary because of the need for some code to run asynchronous. Asynchronous means that for that particular code, it will won't run when the file is originally executed, but when something happens. Lets look at the event handling example again:

button.addEventListener('click', handleBtnClick);

function handleBtnClick(event) {
  console.log('I have been clicked');
}
Enter fullscreen mode Exit fullscreen mode

The handleBtnClick function work asynchronously, it does not log "I have been clicked" until the function has been physically clicked by the user. By using callback functions we are able to execute any number of instructions when certain events occur. Those events may also be initiated when a certain time has passed by using the .setTimeout function.

Conclusion

I hope by the time you are reading this you have a better understanding of what a callback function is, how it is used and why we use it. They are an important and exciting tool to implement in your own code in order to make your code more interactive.

Resources

Top comments (0)