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:

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:

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:

function myDisplayer(some) {
    console.log(some)
}
function myCalculator(num1, num2, myCallback) {
    let sum = num1 + num2
    myCallback(sum)
}
myCalculator(5, 5, myDisplayer)

Example Code 4:

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:

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