Callback in JavaScript
Callback is also called the higher order function in javaScript.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
function greeting(name) { alert('Hello ' + name); } function processUserInput(callback) { var name = prompt('Please enter your name.'); callback(name); } processUserInput(greeting);
The above example is a synchronous callback, as it is executed immediately.
let x = function(){ console.log("I am called from inside a function"); }; let y = function(callback){ console.log("Do something"); callback(); }; y(x);
Multiple callabcks
let add = function(a,b){ return a+b; }; let multiply = function(a,b){ return a*b; }; let substraction = function(a,b){ return a-b; } let calculate = function(num1,num2,callback){ return callback(num1,num2); } console.log(calculate(5,3,add));
Anonymous callback function
let calculate = function(num1,num2,callback){ return callback(num1,num2); } console.log(calculate(5,3,function(a,b){ return a*b; }));