Only Global and Function Scopes
This writes “2” to the console. In a c-like language the variable A would be “redeclared” and the assignment won’t take any effect out of the if block.
However, if the variable was declared in a function, it would override the outer (global) scope, as follows
In the function the value of à
is "2", but when code flow is returned fromf
,a` referes back to the global scope, having the value “1”.
Simple, isn’t it?
A more problematic example
comes from the outer scope. And what is the outer scope? The loop? No, the function! After the loop ends ìwill be equal to 3, and that is what what the event listener will use lately when it is called. One can think about this as if ì` is declared at the top of the function’s code (this concept is usually called hoisting).
To solve it one must provide a fresh ì
Immediate functions are simply defining a anonymous functions and calling them right away, as follows:
This works because a function definition is a expression that returns a function value that is called using the
()function call operator.
So for our buttons example, immediate functions can be employed to create a closure that associates the ì`index value with the button’s click event listener. The following code now works as expected:
Note the creation of the the event listener: a new anonymous function is returned with the proper index in scope (using a closure, so f***ing functional!).