Reputation: 35
How are callback functions different from a helper function in javascript? if they are both accepting functions as arguments?
Upvotes: 1
Views: 1304
Reputation: 7324
There nothing like callback function, it just refers to the function(named function) or anonymous function that is being called by a function or piece of code once it transitions to another state or after an event occurs.
Upvotes: 0
Reputation: 202836
They are both functions, but the difference I suppose is how they are referenced and/or used.
Helper functions are just called "whenever" when they are in scope. Callbacks are typically passed elsewhere and invoked with some parameters.
I hope the below snippet explains it.
// Just some function, what does it do?
const someFunction = (...args) => console.log("I'm a helper function", ...args);
const useAsHelperFunction = () => {
// Called directly
someFunction('used as helper function');
};
const useAsCallback = callback => {
// invoking callback
callback('used as callback function');
};
useAsHelperFunction();
useAsCallback(someFunction);
Upvotes: 0
Reputation: 1973
Callbacks are the functions that are passed as a function argument and are performed after a particular event such as resolving of a promise.
Helper functions are the normal functions that are called at any point of time when the code execution is taking place. Mostly, helper functions are wrapped inside another function.
Example of callback function:
const fun = (callback) => {
setTimeout(callback, 3000);
};
fun(() => {
console.log('callback function');
});
Example of helper function:
const factorialOfNNumbers = (...numbers) => {
const helperFact = (n) => {
if (n ===1 || n === 0)
return n;
return n * helperFact(n-1);
};
return numbers.map(n => helperFact(n));
};
console.log(factorialOfNNumbers(2, 3, 4));
Upvotes: 3