What is a callback function in JavaScript with an example?
A function passed as an argument to another function is called a callback function and this technique allows a function to call another function. A callback function gets executed after the execution of another function gets finished.
Example
function isOdd(number) {
return number % 2 != 0;
}
function filter(numbers, fn) {
let results = [];
for (const number of numbers) {
if (fn(number)) {
results.push(number);
}
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];
console.log(filter(numbers, isOdd));
Answer // [ 1, 7, 3, 5 ]
The benefit of using this feature is that you can wait for the result of a previous method call and then execute another method call.
BY Best Interview Question ON 10 Aug 2022