A callback is a function that is passed as an argument to another function. |
By using a callback, you can pass the myCallback function as an argument to the myCalculator function, allowing the calculator to execute the callback once the calculation is complete.
function myDisplayer(some) { document.getElementById(“demo”).innerHTML = some; } function myCalculator(num1, num2, myCallback) { let sum = num1 + num2; myCallback(sum); } myCalculator(5, 5, myDisplayer); |
In the example above, myDisplayer is referred to as a callback function.
It is passed as an argument to myCalculator().
// Create an Array const myNumbers = [4, 1, –20, –7, 5, 9, –6]; // Call removeNeg with a callback const posNumbers = removeNeg(myNumbers, (x) => x >= 0); // Display Result document.getElementById(“demo”).innerHTML = posNumbers; // Keep only positive numbers function removeNeg(numbers, callback) { const myArray = []; for (const x of numbers) { if (callback(x)) { myArray.push(x); } } return myArray; } |
In the example above, (x) => x >= 0 is a callback function, which is passed as an argument to removeNeg().