Javascript callbacks

What is a callback?

                 In javascript, we can pass a function as an argument to another function. The callback function is a function that we can pass to another function that can be executed after the completion of the function/code.

 

function test(a, b, callback) {
let sum = a + b;
callback(sum);
}

let result = test(10, 3, (sum) => {
console.log('sum is ' + sum);
});

// output
// sum is 13

When to use callback?

1. In asynchronous programming

                Javascript executes code asynchronously which means javascript does wait till the completion of the statement.  it starts the execution of the next statement while the previous statement is not yet finished.

In that case, if we want to execute the code after completion of some other code we can use the callback function.

function test(a, b, callback) {
setTimeout(() => {
callback();
}, 1000);
console.log('first statement');
}

let result = test(10, 3, () => {
console.log('second statement');
});

// output
// first statement
// second statement

 

Add comment