Press "Enter" to skip to content

JavaScript: creating own callback functions

Many methods in JavaScript uses callback functions. Let’s consider e.g. Array “map” method. You can have a variable containing array like: const numbers = [9, 8, 7, 6, 5, 4] and you can chenge all it’s elements by running a “map” method with a callback function which will do the same operation on every element in array, like e.g. multiplying it by 2:

const numbers = [9, 8, 7, 6, 5, 4];
const results = numbers.map((item) => item * 2);

And you can create a callback function in your normal JavaScript code. It’s very easy! Check out code below:

function sumNumbersWithExtension (a, b, callback) {
    var res = a + b;
    
    if(typeof callback === "function") {
        res = callback(res);
    }

    return res;
}


var res1 = sumNumbersWithExtension(1, 2);

var res2 = sumNumbersWithExtension(1, 2, (internalVal) => {
    console.log(internalVal);
    return internalVal * 10;
});

console.log("res1: ", res1); // res1: 3
console.log("res2: ", res2); // res2: 30

So as you can see, by using a callback function inside another function you can have “access” to internal values of parent function in callback function. You can do another operations in parent function, so it gives you a huge flexibility for your code.

Above, we assigned to variable “res1” the same function without callback, and it returned “3”, in second example, we defined a callback function which modified the sum of a + b like internal function inside parent one.

Isn’t it great? 🙂