What is callback ?
In JavaScript, a callback is a function that is passed as an argument to another function and is intended to be executed after the completion of a specific task or at a particular event. Callbacks are commonly used in asynchronous programming, event handling, and other scenarios where you want to execute code in response to some external trigger.
let's see an example:
function getAnswer (num, callback) {
return callback(num)
}
function multiply (num) {
return num*num
}
let ans = getAnswer(10, multiply)
console.log(ans);
//Output
// 100
In the provided code, the getAnswer function takes two parameters: num and callback. It expects a numerical value (num) and a callback function (callback). The getAnswer function then calls the provided callback function with the given numerical value (num) and returns the result.
The multiply function is a simple callback function that takes a number and returns the square of that number (num * num).
multiply: Takes a number as an argument and returns its square.
function multiply(num) {
return num * num;
}
getAnswer: Takes a number (num) and a callback function (callback). It calls the callback with the provided number and returns the result.
function getAnswer(num, callback) {
return callback(num);
}
The getAnswer function is invoked with the numerical value 10 and the multiply function as the callback.
let ans = getAnswer(10, multiply);
The getAnswer function calls the provided callback function (multiply) with the argument 10.
return callback(num);
The multiply function is executed with num set to 10, resulting in the square of 10 (10 * 10), which is 100.
The result (100) returned by the callback function is assigned to the variable ans.
let ans = getAnswer(10, multiply);
Finally, the result (ans) is logged to the console.
console.log(ans); // Output: 100
the getAnswer function serves as a higher-order function that takes a numerical value and a callback function. It uses the callback function to perform a specific operation.
Callbacks in Event Handling:
// Example of using a callback for event handling
const btn = document.getElementById('myButton');
btn.addEventListener('click', function() {
console.log("Button clicked!");
});
In this example, the anonymous function passed as a callback is executed when the 'click' event occurs on the button element.