I want to have a clear understanding of callback functions in javascript and the following are 2 of my questions, these questions may be very basic but I guess it will help in clarifying the concept of callbacks:
1.Do all the callback functions execute asynchronously which means that even if the task is not slow,they run on a separate process and are put back on the event queue to be executed at a later time?
2.In my sample code below,there are 3 functions, a simple add function of 2 numbers,a normal function which calls the add function and a function which uses a callback function,the results will be the same in console,now,apart from the advantage of shorthand and anonymous function, how the calculate() and calculate1() differ in the execution.
And also I went through the thread Why use callback in JavaScript, what are its advantages? in which it is explained that why we need callbacks specifically for asynchronous programming,however I want to know how all the callbacks simple or complexed are handled,in my code below where I am using a simple callback is not an asyncronous function like setTimeOut or setInterval, it is simply a callback,so how will it be handled or executed differently. Thankyou!
function add(x,y){
return x + y;
}
function calculate(x,y,compute){
return compute(x,y);
}
function calculate1(x,y){
return add(x,y);
}
var a = calculate(5,4,function(x,y){return add(x,y)});
var b= calculate(5,4,add);
var c= calculate1(5,4);
console.log(a);
console.log(b);
console.log(c);