Understanding callback functions in Javascript - ES6
Callback functions - A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished. we need to understand in JavaScript functions are executed in the order which they are called and not in the order defined.
function myFirst() {
console.log("Hello");
}
function mySecond() {
console.log("Goodbye");
}
mySecond();
myFirst();
/*expected output:
Goodbye
Hello
*/
Sometimes you would like to have better control over when to execute a function. Suppose you want to do a calculation, and then display the result. or take the input from the user, process it and then only display the result.
function greeting(name) {
console.log(`Hello, ${name}`);
}
function processUserInput(callback) {
const name = 'Manjunath';
callback(name);
}
processUserInput(greeting);
/*expected output:
Hello, Manjunath
*/
function myDisplayer(some) {
console.log(some);
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
/*expected output: 10 */
In the real world, callbacks are most often used with asynchronous functions. A typical example is JavaScript setTimeout().
When you pass a function as an argument, remember not to use parenthesis.
setTimeout(myFunction, 3000);
function myFunction() {
console.log("I love You !!");
}
/*expected output: I love You !! */
Comments
Post a Comment