Title: What is a callback function?
Course: Fall 2023 - WEBD 164 (41934) > Section: Week 5 (Sep 18) How to Use Functions and Events

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

myCalculator(5, 5, myDisplayer);



MyDisplayer is the callback function!

Now look at this. A function that removes negative numbers from 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.
It is passed to removeNeg() as an argument.