Closure
Closure is when a function "remembers" (able to access) its lexical scope even when the function is executed in different lexical scope.
Variable amount
belongs to incrementByAmount
s lexical scope. Even though in
line 7
incrementByAmount
is executed and it's return value is assigned to
incrementByFive
it's lexical scope is remembered. We cann see it by looking at
line 8
. Even though outer function is already executed incrementByFive
still
holds on to outer functions lexical scope and is able to access amount
variable which is 5 in this scenerio.
For loop pitfall
Variables declared with var are not local to the loop, they are in the same scope the for loop is in.
Below example shows that a variable declared by var
within a for loop is also available within the parent scope (in this case, the global scope
).
Working for loop
Variables declared with let are local to the statement.
Some links
- Some great examples: Javascript Closures Made Easy
- More great examples: 7 Interview Questions on JavaScript Closures. Can You Answer Them?