Callbacks: How do Functions Access other Functions?

Viewed 50

Well, first see my code:

function cubosSuma(a,b,callback) {
    var res = (a*a*a)+(b*b*b);
    callback(res);
    }
function resultado(res) {
    console.log(res);
    };
cubosSuma(3,2,resultado); //line 8;

What I want to understand is why I can call 'resultado' in cubosSuma (line 8) if it is supposed to be that a function has its own scope. I mean, why is it possible to get to callback(res) from another function?

1 Answers

The function resultado is defined before it is used on the last line of code, so that's how your program know what it is. Not that it matters for Javascript as Javascript uses hoisting which you can read more about at https://www.w3schools.com/js/js_hoisting.asp

callback in the cubosSuma function is just a placeholder name... when you call cubosSuma on the last line of code, it replaces the placeholder callback with the function you pass to it... which is resultado

And using functions within other functions is a feature of Javascript and has been since forever. See this SO article for more info - Calling a Function defined inside another function in Javascript

Related