In JavaScript, a callback is a function that is passed as an argument to another function and is intended to be executed after the completion of that function. Callbacks are a fundamental concept in asynchronous programming, allowing you to define what should happen once a particular task or operation is finished.
Here we start from a basic way..........
Imagine you have a friend, and you ask your friend to do something for you, like bringing you a cup of coffee. After your friend is done, they let you know by calling or texting you. In this situation:
You are the main program or function. Your friend is the callback function. In programming, a callback is similar. It's like asking a function to do something for you, and once it's done, the function tells you by calling another function, which we call the "callback" function.
Here's a simple analogy:
Imagine this as your friend (callback function)
// Imagine this as your friend (callback function)
function bringCoffee() {
console.log("Here's your coffee!");
}
// This is you (main program)
function askFriendToDoSomething(callback) {
console.log("Asking a friend to do something...");
// Pretend your friend is doing something here
// In this case, it's just waiting for 2 seconds using setTimeout
setTimeout(callback, 2000);
}
// You ask your friend (callback) to bring coffee
askFriendToDoSomething(bringCoffee);
When you run this code, you'll see:
Asking a friend to do something...
Here's your coffee!
In this example:
You have a function called
askFriendToDoSomething
, which takes a callback function as an argument (like asking your friend to do something for you).The
askFriendToDoSomething
function just pretends to do something by usingsetTimeout
(imagine your friend waiting for 2 seconds).After 2 seconds, it calls the callback function (
bringCoffee
), which is like your friend telling you, "Here's your coffee!"
So, callbacks are just a way to pass functions as arguments to other functions and execute them when needed. They are commonly used in JavaScript for handling asynchronous operations, like fetching data from a server, reading files, or any task that takes some time to complete.