One Pager Cheat Sheet
Closures
are relatively new and potentially confusing, but with practice and the help of MDN docs, we can finallyunderstand
them!Understanding the Scope of Execution
is essential to properly utilizeclosures
, as a programwithout functions
will only have oneglobal scope
.- The program outputs 27 because the
console.log()
statement references the initial declareda
value before the sum function changes it. - A
stack
data structure is used to store a newly created local scope when a function is called, which ispopped off
the stack and destroyed when the scope of execution ends. - Understanding nested functions and their ability to access
globalScope
variables is essential for fully comprehending the concept ofclosures
. - The
variable
declared in theglobal scope
is available inside the inner function, but the other way around is not possible and will throw an error. - The
ReferenceError
thrown is due to innerLocalScope not being accessible from the global scope, as it is scoped to the innerScopeCheck() method. - The output of this code snippet is determined by the scope of the variables used in the
innerScopeCheck
function, withinnerLocalScope
being limited in scope. - The code snippet demonstrates the concept of
closure
by showing how an incremented value of a variable can be "remembered" across subsequent executions of a function. - A JavaScript closure combines a function with its
surrounding state
to create a new entity, which can be further investigated using theInspect
command in Google Chrome. - A JavaScript
closure
is a function combined with thelocal
scope in which it was declared and is maintained after the outer function has finished executing. - Closures offer powerful flexibility to remember the associated environment of an
innerScopeCheck()
method to have access to changed values of variables and utilize it in code, as demonstrated in thisscopeCheck()
example.