Callback functions

Callback functions are a way to call functions within another function. This sounds like functionception, so we should probably show this with an example:

let x = function(){
console.log("This is a call within the function x");
};

let y = function(callback){
console.log("This is a call within the function y");
callback();
};

y(x);
// "This is a call within the function y"
// "This is a call within the function x"

The above shows an example of how callback functions are used. The y function takes an argument called callback, and then get's called within the function. From there, we call on y with the argument x.

Calculator example:

Lets say we were to build a calculator:

calc = function(a, b, calcType) {
    if (calcType === "add") {
        return a + b;
    }
    else if(calcType === "multiply") {
        return a * b;
    }
};

calc(2, 3, "add");        // 5
calc(2, 3, "multiply");    // 6

This is all good, but we can clean this up by refactoring it. This is simply separating a single function into multiple functions:

add = function(a, b) {
    return a + b;
};

multiply = function(a, b) {
    return a * b;
};

calc = function(a, b, callback) {
    return callback(a, b);
};

calc(2, 3, add);        // 5
calc(2, 3, multiply);    // 6

Callback will execute whatever function it refers to. We can even do some funky things:

calc(2, 3, function(a, b){ return a - b});
// -1

Running an anonymous function works with this as well.

An anonymous function is one that is not defined. We use these functions once and then dispose of them, as we have no way to call them back again.

results matching ""

    No results matching ""