0

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.

efw
  • 449
  • 3
  • 16

1 Answers1

1

Imagine that B was sometimes passed A, but other times was passed a function named C. If B calls a function directly, it can only ever call that function. But if it's passed a function to call, it can call whichever function it's been passed:

function A() {
    return 'hello';
};

function C() {
    return 'Привет';
};

function B(callback) {
    var output = callback();

    console.log(output);
    console.log("goodbye")
};

B(A);
// => 'hello'
// => 'goodbye'
B(C);
// => 'Привет'
// => 'goodbye'

You can't do that without the callback.

Really, this is why arguments are powerful in general. Passing different arguments to a function allows code to be dynamic in ways it couldn't be without them (or an equivalent mechanism).

  • Brilliant, Luke, this is what I was looking for. This is a case of not being able to see the forest for the trees. Thanks so much. – efw Oct 19 '19 at 02:07