Javascript callback in simplest terms
In JavaScript, a callback is a function that is passed as an argument to another function and is called by that function. The purpose of a callback is to allow a function to execute some code after another function has completed its task.
Here’s an example of a simple JavaScript function that takes a callback as an argument:
function doSomething(callback) {
console.log("Doing something...");
callback();
}This function takes a single argument called callback, which is a function that will be executed after the doSomething() function has completed its task. The console.log() statement is just a placeholder for some real work that the function would perform.
Get shoeb sayyed’s stories in your inbox
Join Medium for free to get updates from this writer.
Now, let’s create a function that we can pass as a callback to doSomething():
function sayDone() {
console.log("Done!");
}This function simply logs a message to the console to indicate that it has been called.
Finally, let’s call doSomething() and pass sayDone() as a callback:
doSomething(sayDone);When this code is executed, the following output will be logged to the console:
Doing something...
Done!This is because the doSomething() function first logs "Doing something...", then calls the callback function that was passed to it (in this case, sayDone()), which logs "Done!" to the console.
In summary, a callback is a function that is passed as an argument to another function and is executed after that function has completed its task. They are a powerful tool for creating asynchronous and event-driven code in JavaScript.










