Skip to content

Instantly share code, notes, and snippets.

@dylanjha
Created August 1, 2013 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanjha/6131199 to your computer and use it in GitHub Desktop.
Save dylanjha/6131199 to your computer and use it in GitHub Desktop.
Javascript Scope. Most languages with C syntax have block scope. All variables defined in a block ( curly braces ) are not visible from outside of the block. Unfortunately, JS does not have block scope, even though its block syntax suggests that it does. JS has function scope. That means that the parameters and variables defined in a function ar…
var foo = function(){
var a = 3
,b = 5;
var bar = function(){
var b = 7
,c = 11;
//Right here: a == 3, b == 7 and c == 11
a += b + c
//Now, a == 21, b == 7, and c == 11
};
//Here a == 3, b == 5, and c is undefined
bar(); //invoke the bar function
//Finally, a == 21, b == 5.
//Notice that "c" is out of the scope here, so when the bar() function assigned c,
//the outer function couldn't get that value.
//However, since a was in the scope of the outer function, the bar function could modify it.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment