Sitemap
Saravanan Software Programmer

Saravanan Software Programmer

Experienced Angular developer proficient in HTML, CSS, JavaScript, TypeScript, RxJS, and NgRx. Passionate about sharing software insights and empowering others.

Callback Function in JavaScript

1 min readMay 27, 2024

--

Press enter or click to view image in full size
Photo by Clark Tibbs on Unsplash

What is callback function?

A callback function is a function that is passed as an argument into another function, which will be invoked within that function at a later time, typically after some task or action has been completed.

function calculate(a, b, callback) {
const result = a + b;
// Invoke the callback function and pass the result as arguments
callback(result);
}

// Define a callback function that logs the result
function callbackFunction(result) {
console.log("The result is:", result);
}

// Call the calculate function with two numbers and the callback function
calculate(5, 3, callbackFunction);

---------

Output: The result is: 8

Why callback function?

Callback functions are like leaving a note for someone, saying “Call me back when you’re done”. In programming, they’re used for similar reasons. When you have a task that takes time to finish, or you want something to happen after an event, you use a callback function. It’s a way of saying, “Hey, do this, and let me know when you’re finished”.

Get Saravanan Software Programmer’s stories in your inbox

Join Medium for free to get updates from this writer.

In JavaScript, callback functions real time examples are like setTimeout run a function after waiting for a certain time, while setInterval repeatedly runs a function at set intervals.

Hope it’s worthy to read✌️.

--

--

Saravanan Software Programmer
Saravanan Software Programmer

Written by Saravanan Software Programmer

Experienced Angular developer proficient in HTML, CSS, JavaScript, TypeScript, RxJS, and NgRx. Passionate about sharing software insights and empowering others.