Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Callbacks

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.

Example

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

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

myCalculator(55, myDisplayer);

In the example above, myDisplayer is referred to as a callback function.

It is passed as an argument to myCalculator().

Example

// Create an Array
const myNumbers = [41, –20, –759, –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().