Function Call Issue

Hello, I’ve been researching this all day and have come up empty. Can someone explain what is going on here? See code below. I thought outer and inner functions would each run three times because I called the outer function three times. Scroll all the way down to see my comments at the bottom about why I’m confused.

<script>
    
window.onload = function() {
                
    var outerFunction = function() {
           
        var logThis = "Outer function ran.";
        console.log(logThis);
            
        var innerFunction = function() {
                
            var logThisAlso = "Inner function ran.";
            console.log(logThisAlso);
            };
            
        return innerFunction;
            
        };                  
    
    var functionCall = outerFunction();
        functionCall();
        functionCall();
    
/*

Result:

    Outer function ran.
    Inner function ran.
    Inner function ran.
    
    
Why not returning the below?

    Outer function ran.
    Inner function ran.
    Outer function ran.
    Inner function ran.
    Outer function ran.
    Inner function ran.

*/

};
</script>

Hello!

When you execute this:

var functionCall = outerFunction();
        functionCall();
        functionCall();

This happens:

  1. The outerFunction gets called. This defines the innerFunction (without calling it) and returns a reference to it, hence the functionCall gets a reference to innerFunction. The innerFunction has not been called yet.
  2. The first functionCall is invoked. Since it’s a reference to the innerFunction, the message Inner function ran is logged to the console.
  3. The previous step is repeated.
  4. Program execution is finished.

You can see the execution of your code here, which may help you understand what’s happening :slight_smile:.