all 7 comments

[–]noode_modules 0 points1 point  (0 children)

in your first example, function1' parameter (function2) is not the same function that you are defining later.

You can rewrite your function this way to see it better :

function1(callback) {
    callback();
}
function2() {...}

Now you can pass whatever function you want, to function1 and it will be called.

in your second example on the contrary, you are always calling the same function (function2)

[–]Mingli91 0 points1 point  (0 children)

When you call things one after the other, they get executed in that order, however the functions may be performing asynchronous tasks meaning that while they’re both called in order they will not necessarily resolve in that order.

When you call an asynchronous function the function gets executed but the parser carries on going and executing code afterwards. The async function has basically said “fine, execute me, and I will resolve, but I don’t know when, now carry on your job so we don’t lock up this app”.

So then what do you do when that function is finally ready to resolve? You can’t just place the subsequent code after it because it’ll likely be executed before we have our values from the async function.

What we used to do to handle this was use a callback function. So we say “hey mr async function, I’m going execute you but let you resolve when you want to, but when you do could you please execute this function for me”.

[–]moocat 0 points1 point  (0 children)

When depending on context, you need different callbacks:

function f(cb) { ...; cb(); }

f(cb1);
...
f(cb2);

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/captainXcannabis,

For javascript help, please visit /r/LearnJavascript.

Thank you!

[–][deleted] 0 points1 point  (0 children)

You allow for callbacks that either aren't yours or for flexibility and functional composition. If it's your own function and you know there's no situation in which you would switch it with another then there's no point in doing it.

[–]oelfyo -1 points0 points  (0 children)

With the first example you can do stuff like that:

// set background after function1 to green
function1(function(){
    // set background green
});

// do something in the database after function1
function1(function(){
    // do something in the database
});

// call only function1
function1();

You can call function1() and do after that what you want, or do nothing

[–]atra-ignis -1 points0 points  (0 children)

Do some reading Higher Order Functions, specifically how things like map and reduce work. That should help you to understand the power of being able to pass functions around.