Nested functions and lambdas can reference variables defined in enclosing scopes. This can create tricky bugs when the variable and the function are defined in a loop. If the function is called in another iteration or after the loop finishes, it will see the variables' last value instead of seeing the values corresponding to the iteration where the function was defined.
* it increases the risk of introducing a bug when the code is refactored or when dependencies are updated. See an example with the builtin "map" below.
One solution is to add a parameter to the function/lambda and use the previously captured variable as its default value. Default values are only executed once, when the function is defined, which means that the parameter's value will remain the same even when the variable is reassigned in following iterations.
No issue will be raised if the function or lambda is directly called in the same loop. This still makes the design difficult to understand but it is less error prone.
* If the function is NOT a lambda: "Add a parameter to function "FFF" and use variable "XXX" as its default value; The value of "XXX" value might change at the next loop iteration."
* If the function is a lambda: "Add a parameter to the parent lambda function and use variable "XXX" as its default value; The value of "XXX" value might change at the next loop iteration."
=== Highlighting
Primary: the first time the variable is used in the function/lambda
Secondaries:
* every assignment of the variable in the enclosing loop