In this post I go through some examples of Javascript Scopes using nested functions. The main rule is that when a variable is referenced, Javascript looks to the local scope first then progressively moves outward until it finds a definition for the variable or reaches the global scope. If the variable was not defined in the global scope, Javascript will create the variable in the global scope.

scope #1 – walks up until it hits the global scope and finds a definition. If line #1 wasn’t defined, Javascript would create a global variable called foo and set it to undefined.

scope #2 – uses local scope

scope #3 – reaches out to bar scope

scope #4 – parameter reaches out to global scope

scope #5 – parameter uses local bar scope

scope #6 – parameter not passed so it is undefined