DEV Community

saiarlen
saiarlen

Posted on

Q2. Explain what a callback function is and provide a simple example.

Ans. A JavaScript callback is a function which is to be executed after another function has finished execution.

Below is an example of a simple callback function that logs to the console after some operations have been completed.

function modifyArray(arr, callback) {
  // do something to array here
  arr.push(250);
  // then execute the callback function that was passed
  callback(); 
}

var arr = [1, 2, 3, 4, 5];

modifyArray(arr, function() { //calling function
  console.log("array has been modified", arr);
});

Enter fullscreen mode Exit fullscreen mode

2 Of 20 Js Interview Questions🙂
Any comments or examples would be appreciated🙃

Top comments (0)