DEV Community

Megalraja
Megalraja

Posted on

Understanding Callback Function in JavaScript

while learning javascript, I came across a concept called a callback funtion.

At first, the name sounds complicated. But the idea is actually pretty simple.

What is a callback function?

A callback function is a function passed into another function as an argument, which can be called later.

for example:

function greet(name) {
    console.log("Hello " + name);
}

function processUser(callback) {
    callback("Alex");
}

processUser(greet);
Enter fullscreen mode Exit fullscreen mode

Here, greet is passed to processUser as an argument.

Inside processUser, we call:

callback("Alex");
Enter fullscreen mode Exit fullscreen mode

So greet() gets executed.

Why do we use Callbacks?

Callbacks are useful when we want one function to run another function after something happens.

or example:

function calculate(a, b, callback) {
    let result = a + b;
    callback(result);
}

calculate(10, 20, function(result) {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode
Output:

30
Enter fullscreen mode Exit fullscreen mode

The callback receives the result after the calculation is completed.

Callbacks are especially important in JavaScript because they are commonly used with events, timers, and asynchronous operations.

Simple way to remember
Function → Does the work
Callback → Function passed to another function
callback() → Executes the passed function

Top comments (0)