What is callback?

callBack :

  • An event handler is a particular type of callback,

  • A callback is a just function, that passed into another function,with the expatiation that the call Back will call at the particular time.

  • We just saw , callBacks are used to be the main way asynchronous functions were implemented in java-script.

  • callBack based functions are hard to call the function,that accept a function.This is common situation if you need to perform some operations that breaksdown into a series of asynchronous functions.

function obj(init, callback) {
    const result = init + 1;
    callback(result);
}

function obj1(init, callback) {
    const result = init + 2;
    callback(result);
}

function obj2(init, callback) {
    const result = init + 3;
    callback(result);
}

function object() {
    obj(0, (result1) => {
        obj1(result1, (result2) => {
            obj2(result2, (result3) => {
                console.log(result3);
            });
        });
    });
}

object();

The code defines three functions (obj, obj1, obj2) that take an initial value and a callback function.

  1. The object function is defined, which chains these functions together, passing their results to each other in sequence.

  2. When object is called, it initiates a nested series of function calls, starting with obj, then obj1, and finally obj2.

  3. Each function adds a different number (1, 2, or 3) to the initial value and passes the result to the next function in the chain.

  4. The final result of init + 1 + 2 + 3 is logged to the console.

  5. Thus, the output is 6, showing the cumulative result of adding 1, 2, and 3 to the initial value of 0.