Question about the difference between mainFunction3 and mainFunction2

I’m not understanding how the unscoped function (mainFunction3) behaves differently from the scoped function, (mainFunction2).

mainFunction3 also freezes the variable i even though it doesn’t leverage capturing. The output is
I can easily change code on line 8 to
listFunctions.push(innerFunction(i * 100));
to make the output identical to the output of mainFunction2()

Could you clarify a bit more on the difference? Thanks!

Course: Learn TypeScript: The Complete Course for Beginners - Learn Interactively
Lesson: TypeScript Scope is JavaScript Scope - Learn TypeScript: The Complete Course for Beginners

Hi @Yunfei_Xie !!
The difference between mainFunction2 and mainFunction3 lies in how they handle the scoping and capturing of variables.

In mainFunction2, the variable innerFunction is assigned an anonymous function that captures the variable variableCapturedByTheInnerFunction. The captured variable retains its value even after the surrounding block (the if statement) has executed. When innerFunction is called later, it returns the captured variable, which by that point has been changed to "Changed". Therefore, the output of mainFunction2 is "Changed".

In contrast, mainFunction3 behaves differently because it uses a for loop to iterate from 10 to 14. Inside the loop, innerFunction is assigned a new function for each iteration, and it takes param1 as a parameter. The variable param1 is a local variable specific to each invocation of innerFunction and is not captured from an outer scope.

The listFunctions.push(innerFunction(i)) line in mainFunction3 immediately invokes innerFunction with the current value of i as an argument and adds the returned value to the listFunctions array. As a result, the array contains the return values of each invocation of innerFunction with different values of i. When the loop ends, the listFunctions array holds five functions, each returning a different value.

If you modify the line to listFunctions.push(innerFunction(i * 100)), you’re passing a different value to each innerFunction. This will result in the same behavior as mainFunction2, where the captured variable is updated within each iteration.

In summary, mainFunction2 captures and shares the same variable across different invocations of innerFunction, while mainFunction3 creates separate instances of innerFunction with different parameters for each iteration. The difference in behavior stems from how scoping and capturing work in JavaScript.
I hope it helps. Happy Learning :blush: