javascriptcallbackinvocationfunction-reference

Why do callbacks have to be a function?


I keep on seeing:

() => execute code

instead of just

execute code 

in callbacks. I am not passing in any parameters, so why does () => execute code work but execute code doesn't? Aren't they the same thing since a function just represents some lines of code? I see similar things in other languages as well like java where lambda is used

Thank you.


Solution

  • The difference is that () => console.log('execute code') is a function definition, whereas console.log('execute code') is a function invocation.

    The code within the body of a function definition does not run until the function is invoked.

    var double = (num) => console.log(num + num) // function definition, does nothing

    double(2) // function invocation, logs 4 to the console

    When you pass a function definition in as an argument to a function invocation, you are making the passed in function definition available to be accessed or called within the body of the invoked function.

    Conversely, if you pass a function invocation, say, double(2) in as an argument to another function invocation, you are making the return value of double(2) (in this case undefined since console.log has no return value) available in the body of the function it is being passed into.

    Example:

    var double = (num) => console.log(num + num)
    
    var invokeCallbackAfterFiveSeconds = (callback) => {
      setTimeout(callback, 5000);
    };
    
    //Passing in a function definition below...
    
    invokeCallbackAfterFiveSeconds(() => double(3));
    // ^ Will log 6 to the console after a five second delay
    
    
    //Passing in a function invocation below...
    
    invokeCallbackAfterFiveSeconds(double(4));
    // ^ Will log 8 to the console immediately, then do nothing else.