Skip to content

Instantly share code, notes, and snippets.

@CodeDraken
Last active June 9, 2019 14:40
Show Gist options
  • Select an option

  • Save CodeDraken/7dc43ed70b2d5180e625a89c7ae01986 to your computer and use it in GitHub Desktop.

Select an option

Save CodeDraken/7dc43ed70b2d5180e625a89c7ae01986 to your computer and use it in GitHub Desktop.
scope and scope chain example with comments
// scope & scope chain commented
// was declared globally, outer reference is global
function a() {
// variable created inside context of a
var myOtherVar = 'inside A'
// b called inside a, but was lexically declared in the global context
b()
}
// was declared globally, outer reference is global
function b() {
// variable exists in b
var myVar = 'inside B'
// goes up to the global context, fetches myOtherVar and logs it
console.log('myOtherVar:', myOtherVar)
// was declared inside b, outter reference is b
function c() {
// goes into the context of function b and logs myVar
// it stops after finding the variable
// meaning it does not go up again to the global scope unless it needs to
console.log('myVar:', myVar)
}
c()
}
// global variables
var myOtherVar = 'global otherVar'
var myVar = 'global myVar'
a()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment