I'm a little confused, not about what callbacks are used for but because I see callbacks used in scenarios often where it seems like passing a function as an argument to another function isn't necessary because you can just invoke the function you want invoked after the code in the current function is finished executing. For example:
function hello( a , b ) {
var result = a + b;
myFunction();
}
myFunction() {
//code
}
hello(1,2);
What's confusing is, I've seen a lot of examples where a callback is being used in a scenario just as simple as the first code I wrote where it seems to me a callback isn't needed at all:
function hello(a, b, callback) {
var result = a + b;
callback();
}
myFunction() {
//code
}
hello(1, 2, myFunction);
I used a callback there but I could've just called the function myFunction
after the code executed without passing myFunction
as an argument. I understand a framework or library doesn't know the name of the function you'll want called after code is finished executing so passing the function you want called later as an argument seems to make sense then but when you know the name of the function you want invoked after whatever code is executed in a function, why not just invoke it just as I did in the first example I gave? I would appreciate your help. Thanks