DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Callback Function in JavaScript

A callback function is a function passed as an argument to another function so that it can be called later.

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

function user(callback) {
    callback("Sajin Joe");
}

user(greet);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Sajin Joe
Enter fullscreen mode Exit fullscreen mode

Callback with a simple calculation

function calculate(a, b, callback) {
    console.log(callback(a, b));
}

function add(x, y) {
    return x + y;
}

calculate(10, 20, add);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Callback with setTimeout()

setTimeout(function() {
    console.log("Hello JavaScript");
}, 2000);
Enter fullscreen mode Exit fullscreen mode

Output: Hello JavaScript after approximately 2 seconds.

The function passed to setTimeout() is a callback. The timer schedules it to run later.

Top comments (0)