What's the difference between calling a function and returning a function?

javascript, jquery, return

Solution

In the second example you're not actually returning the function but rather the result of having executed the function. (Considering the execution of code from right-to-left in this case.)

To illustrate, change your first example slightly:

$('form').submit(function(){
    var result = checkForm();
});

As you can see, the function is executed and a result is returned from the function. It's just that nothing is ever done with that result. It immediately falls out of scope as the anonymous function completes, fading into antiquity.

Slightly modify the second example to further illustrate:

$('form').submit(function(){
    var result = checkForm();
    return result;
});

Just as with the first example, `checkForm` is executed and its result stored in a variable. Then that value is returned from the anonymous function. Naturally, this process can be in-lined such that the temporary variable isn't needed:

$('form').submit(function(){
    return checkForm();
});

The order of operations doesn't change, `checkForm` is executed, returns a result, and that result is returned from the anonymous function.

You could return the function itself, having not actually executed it:

$('form').submit(function(){
    return checkForm;
});

Since functions are "first-class citizens" in JavaScript and can be passed around like any other variable, this would return an actual function and not the result of the function. It would be assumed that calling code would probably end up executing the function. However, in this case (a `submit` handler), that of course wouldn't make sense, as it's expecting a boolean value and not a function.

Problem

I'm using the checkForm function to validate a simple form. When the user press submit, run checkForm. What's the difference between the first and second example? Example 1. ``` $('form').submit(function(){ checkForm(); }); ``` Example 2. ``` $('form').submit(function(){ return checkForm(); }); ```

Original source