Sushmita Pandey
Sushmita Pandey's Blog

Sushmita Pandey's Blog

A simple explanation of Callback functions in JavaScript

A simple explanation of Callback functions in JavaScript

Sushmita Pandey's photo
Sushmita Pandey
ยทNov 30, 2021ยท

3 min read

Hi everyone! ๐Ÿ‘‹ In this post we will take a deep dive into callback functions.

Suppose you created a function called add2 which added 2 to the number it was passed:

function add2(num) {
    return num = num + 2;
}

console.log(add2(3)); // 5

If we wanted to call this function for an array of numbers, we would use the map method for arrays, which would go over all the elements of the array and perform any specific operation:

const numbers = [3, 6, 1, 7, 8];
const result = numbers.map(add2);
console.log(result); // [5, 8, 3, 9, 10]

We passed the add2 function as an argument to map function. So the add2 function is a callback function. A callback function is a function that is passed to another function. The function receiving the callback function is a Higher-order function.

Why do we need callback functions?

JavaScript is a single threaded language and all the code runs sequentially (line by line from top to bottom). Sometimes we need to perform some operations asynchronously, like we may want some particular code to run after a task has finished. This style of programming is asynchronous and this is where callback functions are put to use.

We can create a callback by passing a function as a parameter to another function that runs a task to ensure that it does not get executed before the task has completed.

Event listeners with callback functions

Let's look at another example of callback functions with event listeners. Let's say there's a button in our UI:

<button id='callback'>Book Now</button>

So we want the code to do something whenever the user clicks on the button. For this we will add an event listener to the button using the addEventListener method, which takes the event type as the first argument and the callback to be fired when the event occurs as second.

function handleButtonClick() {
    console.log('Button was clicked');
}

document.getElementById('callback').addEventListener('click', handleButtonClick);

Here handleButtonClick is a callback function to addEventListener.

Using Anonymous functions

We can also pass anonymous functions as callbacks:

const numbers = [3, 6, 1, 7, 8];
const result = numbers.map(function(num) {
    return num = num + 2;
});

This function is directly being defined in the parantheses of map and it has no name, which makes it anonymous.

Using Arrow functions

Alternatively, we can also pass arrow functions which were defined in ES6:

const numbers = [3, 6, 1, 7, 8];
const result = numbers.map((num) => num + 2);

Arrow functions are shorter than regular functions, and they come especially handy when writing callback functions.

A Downside

Callbacks are great for simple use cases, however if there are a lot of levels of nesting, the code quickly becomes difficult to manage.

window.addEventListener('load', () => {
  document.getElementById('callback').addEventListener('click', () => {
    setTimeout(() => {
      numbers.map((num) =>  {
      // do something
      })
    }, 2000)
  })
})

This condition is also known as callback hell. Thankfully, Javascript introduced Promises and Async/await to help us write asynchronous JavaScript code in a much cleaner and more manageable way. We will explore them in detail in the coming articles.

That's it for this article! If you like this post please share it with your friends ๐Ÿ˜Š For any questions feel free to ping me on Twitter .

Happy coding! ๐Ÿ‘ฉโ€๐Ÿ’ป

ย 
Share this