function can access all variables defined inside the function, like this:
But a function can also access variables defined outside the function, like this:
In the last example, a is a global variable. In a web page, global variables belong to the window object. Global variables can be used (and changed) by all scripts in the page (and in the window).
In the first example, a is a local variable. A local variable can only be used inside the function where it is defined. It is hidden from other functions and other scripting code.
Global and local variables with the same name are different variables. Modifying one, does not modify the other.
Variables created without a declaration keyword (var, let, or const) are always global, even if they are created inside a function.
Global variables live until the page is discarded, like when you navigate to another page or close the window.
Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.
A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function’s scope, and (3) global variables.
the above example, variables from innerFunc, outerFunc, and the global namespace are all in scope in the innerFunc. The above code will therefore produce the following output:
outerArg = 123; innerArg = 456; outerVar = a; innerVar = b; globalVar = xyz
Surprising the output of the following code will not display the values 0, 1, 2, 3, and 4 as might be expected; rather, it will display 5, 5, 5, 5, and 5.
The reason for this is that each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in
i, which was 5.
Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows:
A closure is a function having access to the parent scope, even after the parent function has closed.