Skip to main content

Command Palette

Search for a command to run...

Masterclass on Callbacks in JavaScript

Updated
β€’5 min read

What are we gonna Study?

Hey there folks, Hope you are doing great in your life, let's learn about callbacks today, So basically the topics we'll be covering today are

  1. What a callback function is

  2. Why callbacks are used in asynchronous programming

  3. Passing functions as arguments

  4. Callback usage in common scenarios

  5. Basic problem of callback nesting

I want you to gather all your focus here (take it away from your crush), and with this let's begin!


What is a Callback Function?

  • They are basically functions which are passed as an argument to another function

  • They are meant to be executed after a specific task, or event or any asynchronous operation.

  • Before promises and async/await existed, It was the way to write asynchronous program.

Here is how a callback looks like

// 1
function greet(name, callback) {
  console.log("Hello, " + name + "!");
  callback();
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("Alice", sayGoodbye);

// ************************************************* //

// 2
console.log("Starting task...");

setTimeout(function() {
  console.log("Task complete after 2 seconds!");
}, 2000);

console.log("Moving on to other things...");

// ************************************************* //

// 3
const btn = document.getElementById("myButton");

btn.addEventListener("click", () => {
  console.log("Button was clicked!");
});

See, we are just passing one function in the argument of another, that's your callback!


Why callbacks are used in asynchronous programming

  • In the realm of programming, we sometimes need to perform some actions which are asynchronous.

  • In order to do that we use callbacks to do so (though nowadays Promises and Async/Await are used they were the first entity to be able to perform that).

Now, here comes a question why we even do that? right?

The answer is that,

  • See, JavaScript is a single threaded language, so it executes the code line by line.

  • Asynchronous code takes time to execute, and that is why JavaScript Engine stops at asynchronous code. (The code where JavaScript Engine waits for something to get executed is known as blocking code).

So, what callbacks does in this situation is that

  • It allows you to execute your whole code, while executing the blocking code in the background.

  • Basically, your problem of blocking code gets resolved here :)


Callbacks Usage in Common Scenarios

Let's tale some example, just don't get overwhelmed, it's actually easy if you read it like it is πŸ˜…

function getUserId(username, callback) {
    setTimeout(() => {
        console.log("Found ID for: " + username);
        callback(101);
    }, 1000);
}

function getUserProfile(id, callback) {
    setTimeout(() => {
        console.log("Fetched Profile for ID: " + id);
        callback({ name: "Alex", age: 25 });
    }, 1000);
}

function getFriends(profile, callback) {
    setTimeout(() => {
        console.log("Fetched friends for: " + profile.name);
        callback(["Sam", "Jordan"]);
    }, 1000);
}

function getLatestActivity(friends, callback) {
    setTimeout(() => {
        console.log("Fetched activity for friends: " + friends.join(", "));
        callback("Jordan just posted a photo!");
    }, 1000);
}

getUserId("Ved_PandeyOG", (id) => {
    getUserProfile(id, (profile) => {
        getFriends(profile, (friends) => {
            getLatestActivity(friends, (activity) => {
                console.log("Final Output: " + activity);
            });
        });
    });
});

// Timers are added so that the code can be asynchronous, don't get confused on that part πŸ˜…
  • Here, in this code we have declared four functions right?

  • All of them are taking two arguments, one is some kind of data and the second is a callback function.

  • So, basically this is nothing more than one function taking some data, performing some action onto in, and then passing that data to the next function right?

I hope the code doesn't seems inferior to you know πŸ˜…

So, this is how we used callbacks way before when promises and async-await didn't existed...

We actually did something like that we called a function and with the data obtained we called another function and with that data another function and so on...

But that is where we faced a problem...

Drum Rolls πŸ₯

Greetings to the problem...


Problem with Callbacks Nesting

In the above code block, we did something like this

getUserId("Ved_PandeyOG", (id) => {
    getUserProfile(id, (profile) => {
        getFriends(profile, (friends) => {
            getLatestActivity(friends, (activity) => {
                console.log("Final Output: " + activity);
            });
        });
    });
});
  • Now, this level of callback nesting is knwon as The Callback Hell or The Pyramid of Doom

  • The problem here is that right now they are just 4 of them, right?

  • But what if there are 8-10 or more than that, and also this was a very simple example we just called each of the, we didn't performed something extra on that, what if we did that too!

  • The code had eventually became unmanageable and unreadable right?

  • And in order to fix this problem, Promises were introduced...

  • If you want to read about promises, you can click here


Wrap Up!

With this our topic for today ends here!

If you like this blog please share on social media platforms and tag me, I'll be happy to see that :)

If you think something can be improved then please give your feedbacks in the comment section

That was it for today, I'll catch you up in the next blog, until then keep coding and enjoying your dev life πŸ’

JavaScript: Everything you should know

Part 24 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Make Data Readable: Array Flatten in JavaScript

What Are We Gonna Study? Hey there folks, hope you are doing great in your life and having fun in coding! Today we'll be learning about the following topics What nested arrays are Why flattening arr

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!