Masterclass on Callbacks in JavaScript
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
What a callback function is
Why callbacks are used in asynchronous programming
Passing functions as arguments
Callback usage in common scenarios
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 π

