George Ka George Ka - 5 months ago 21
Javascript Question

JavaScript: subtracting two numbers returns undefined using callback function

I am trying to make a very simple program in JavaScript (the simplest I can), in order to understand CallBack functions. I know how the code is beeing executed but it seems logical to return the output but it returns undefined instead. Is there something that I haven't understood? How can I return the output?

Code:

var calc = function(num1, num2, callback){
callback(num1, num2);
alert("Hello")
};

console.log(calc(2,3,function(a,b){
return a-b;
}));


Thank you!

Answer

You need to return a value from calc:

var calc = function(num1, num2, callback){
    var result = callback(num1, num2);
    alert("Hello")

    return result
};

console.log(calc(2,3,function(a,b){
    return a-b;
}));

explanation:

you can write the same code in a different way that might make it easier to understand:

var myCallback = function(a,b){
        return a-b;
    });
console.log(calc(2,3,myCallback );

This way, you can clearly see, that in the time you call calc you are not actually executing the callback function, but only passing it as a parameter.

Now in calc:

var calc = function(num1, num2, callback){
    //Here you actually call the function, so it is being executed and the value 
    //is returned, but it is return in the context of calc function, so in order 
    //for console.log to know about it, you have to return it from calc
    var result = callback(num1, num2);
    alert("Hello")

    return result
};