DEV Community

Cover image for Callbacks in JavaScript
Kunal
Kunal

Posted on

Callbacks in JavaScript

When you writing JavaScript you come across the term callback but you may feel confused. Many newcomers to JavaScript find callbacks hard to understand too.

So In this blog we will cover :

  • What a callback function is
  • Passing functions as arguments
  • Why callbacks are used in programming
  • Callback usage in common scenarios
  • Basic problem of callback nesting

Callback function

A callback is a function that takes another function as an argument to be execute later

They are so common in JavaScript that you probably used callback by yourself without knowing they are callbacks

Lets see how it looks :


const button = document.querySelector('button')
button.addEventListener('click', function () {

  console.log("clicked")
})
Enter fullscreen mode Exit fullscreen mode

Here , in the code we told JavaScript to listen for the click event on the button. If the button is clicked JavaScript will fired the click function

Now i am sure that you understand the term callback function and how they are used. But why ? Why do we need these callback function.


Why callbacks are used in programming

Callbacks are used in two different ways in programming one is synchronous and asynchronous functions

Synchronous Functions

If your code executes from top to bottom , left to right sequentially and wait until one code to finish you code is synchronous

Lets look at an example to make it easier to understand :


const addOne =n => n+1

addOne(1)
addOne(2)
addOne(3)
addOne(4)
addOne(5)
Enter fullscreen mode Exit fullscreen mode

Callbacks are used in synchronous functions when you want a part of the code to be easily swapped with something else.

Asynchronous functions

An asynchronous function is a task that runs in background without stopping your main code

Lets look at an example to make it easier to understand :


setTimeout(() => console.log("Like and share") , 1000)
console.log("Already liked this blog !!!")
Enter fullscreen mode Exit fullscreen mode

So in the above example what we do is simply make a Asynchronous function that will execute after 1sec it will not block the block main thread to execute my another console log


Callback usage in common scenarios

Callbacks are very useful feature in JavaScript that has ample amount of scenarios i will cover 3 here apart from the example which i cover before

  1. API / Data fetching

The most common usage of callbacks are fetching data from the APIs


fetchData((data) => {
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode
  1. File handling (Node.js)

File handling is an important operation in Node.js that allows performing CRUD operations on files


fs.readFile("file.txt", (err, data) => {
  console.log(data.toString());
});
Enter fullscreen mode Exit fullscreen mode
  1. Database operations

In Node.js database operations use callbacks to run code one after another

db.query("SELECT * FROM users", (err, result) => {
  console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

These are some of the example of callbacks that used in a programmer everyday life.


Basic problem of callback

Do you ever heard of the term "Callback Hell" it is a phenomenon where multiple callbacks are nested after each other
It happen when you do an asynchronous activity that's dependent on previous asynchronous activity

This make the code harder to read

Let look into the example :


loginUser("kunal", (user) => {
  getProfile(user.id, (profile) => {
    getPosts(profile.id, (posts) => {
      getComments(posts[0].id, (comments) => {
        console.log("Final Data:", comments);
      });
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

pretty hard right ??

One solution to overcome callback hell is to break the callback function into smaller code or Your JavaScript promises and async / await

If you want to know i have a blog , read 👇



Thanks for reading ! if enjoyed this blog , you can read more on this 👇

Top comments (0)