Callbacks are said to add functionality to higher order functions by passing the value of the callback function (its function definition) -- to the parameter of the 'higher-order' function where it is passed in and executed.
It seems we can accomplish the same thing simply by calling an outside function from within another executing function.
The following better illustrates what I am trying to say.
// ************************ Using a callback ************************************************
function A() { // this is the callback function
return 'hello';
};
function B(callback) { // this is considered a 'higher-order' function because it takes a
// function definition as a parameter. the function definition of A
// -- taken from A in Global memory -- is assigned to callback
var output = callback(); // we call callback and run it
// the value of callback, is assigned to the variable output
console.log(output);
console.log("goodbye")
};
B(A); // logs 'hello' 'goodbye'
// ******* compare the above to calling an outside function from within another function *****
function A() {
return 'hello';
};
function B() {
var output = A(); // we call function A, from inside function B,
// the value returned by A, is assigned to a variable inside B
console.log(output);
console.log("goodbye")
};
B(); // logs 'hello' 'goodbye'
While there is no difference between the 2 in terms of the values they return, there are differences in how they execute.
The callback function takes in the function definition of A and attaches it to a new name called callback. Callback is executed, and run inside the local execution context of callback.
Compare this to what happens when we call A from inside B, A executes in its' own local execution context.
Perhaps this example is too simple to see that there are differences between the 2 that would help me understand when I would use one over the other.