Callback Function in Node.js

A callback function is a function which can be passed as an argument into another function. This callback function can then be invoked inside the outer function.

Callback functions were introduced in JavaScript. Since Node.js built on V8 engine, it also support callback functions.

function doSomething(callback){
    console.log("Done Something");
    callback();
}
function doComplete() {
    console.log("Complete");
}
doSomething(doComplete);

In the above example, doComplete is a callback function. This program can also be written as below, without defining callback function separately.

function doSomething(callback){
    console.log("Done Something");
    callback();
}
doSomething(function(){
    console.log("Complete");
});

Leave a Comment