+ 4
Callback Function v/s Higher order function
Can anyone explain me the difference between callback function and higher order function in Javascript. I know callback function takes a function as an argument and higher order function also takes a function as an argument and also return the function. So again next question is then what is the difference between Returning function and higher order function. Please try to explain it simple because i am beginner in Javascript.
3 odpowiedzi
+ 2
Callback function issues a pointer of a function, so other function can run the function with reference to the pointer.
For example, we have a function
function sum (a, b) {
return a + b;
}
To run this function we call sum()
And the callback of this function is sum.
Another function which have argument of callback, cb
function addition (cb, a, b) {
return cb(a, b);
}
We can use addition function with callback, sum to generate an output:
const out = addition (sum, 1, 2); // out is 3
+ 1
Higher order function takes argument callback too. We use higher order function to add or modify the behavior of a function.
For example:
A higher order function of the sum callback:
function sumMessage (f) {
const msg = "total sum = ";
return (...arg) => {
const out = f(...arg);
return msg + out;
}
}
function sum(a,b) {
return a+b;
}
const out = sumMessage(sum)(1,2)
console.log(out) // "total sum = 3"
// This time, we not only use the sum() function to add 2 arguments, we also use a higher order function, sumMessage to inject a variable,msg.