Author: M Abo Bakar Aslam
Callback
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after a specific task or event has occurred. This concept is widely used in event-driven and asynchronous programming, such as handling user actions, API calls, and file operations.
Callback functions allow one function to control the execution of another function, making programs more flexible and modular.
1. Basic Concept of Callback Function
Example Code 1:
- A function is passed as an argument to another function.
- The receiving function can execute the passed function when needed.
- The callback function simply performs a defined task.
Note: When passing a function as an argument, do not use parentheses.
function c1(){
console.log("Helping.....")
}
function displayHello(data, c1){
console.log(data)
console.log("JavaScript")
c1()
}
displayHello("Web Development", c1)Example Code 2:
- The callback function is defined at the time of passing it as an argument.
- The main function executes the callback and can store its returned value.
- This approach reduces the need for separate function declarations.
function displayHello(data, c1){
console.log(data)
console.log("JavaScript")
let result = c1()
console.log(result)
}
displayHello("Web Development", c1 => "Helping....")2. Callback with Parameters
Example Code 3:
- A function receives another function as a parameter (callback).
- The callback is invoked with computed data.
- The receiving function can rename the callback parameter internally.
function myDisplayer(some) {
console.log(some)
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2
myCallback(sum)
}
myCalculator(5, 5, myDisplayer)Example Code 4:
- A callback function is applied to each element of an array.
- The callback processes each value and returns a result.
- The result is then used or displayed alongside the original data.
function displayHello(data, c1){
console.log("JavaScript")
for (const elem of data) {
let result = c1(elem)
console.log(elem, " is ", result)
}
}
myArray = [0, 1, 2, 3, 4, 5, 6]
displayHello(myArray, (x) => {
if(x % 2 === 0)
return "even"
else
return "odd"
}
)Example Code 5:
- A general-purpose function accepts a callback to perform operations.
- Different callbacks can be passed to perform different tasks (e.g., addition, subtraction).
- This demonstrates reusability and flexibility.
function calculate(num1, num2, callback) {
return callback(num1, num2);
}
// Example usage:
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
//calling functions
console.log(calculate(5, 3, add)) // Should log 8
console.log(calculate(10, 4, subtract)) // Should log 6