Skip to content

Instantly share code, notes, and snippets.

@josephwegner
Created May 26, 2015 20:35
Show Gist options
  • Save josephwegner/a9c866f0a547d0f855e1 to your computer and use it in GitHub Desktop.
Save josephwegner/a9c866f0a547d0f855e1 to your computer and use it in GitHub Desktop.
JS Variable Scope
var foo = 'hello!';
var util = {
setBar: function() {
var bar = 'goodbye!';
},
changeFoo: function() {
foo = 'olah!';
},
sayFoo: function() {
console.log(foo);
},
sayBar: function() {
console.log(bar);
}
};
util.sayFoo(); // logs 'hello!', because foo was created in a parent scope of util.sayFoo
util.changeFoo();
util.sayFoo(); // logs 'olah!', because changeFoo is modifying the foo created in a parent scope
console.log(foo); // also logs 'olah!'
util.setBar();
util.sayBar(); // errors, because bar was created in a scope outside of util.sayBar
console.log(bar); // also errors, because bar is in a child scope
console.log(fileScoped); // errors, because fileScoped was created in another file
module.exports = 'exported thing';
var fileScoped = "you can't see me!"
var thing = require('file1.js');
console.log(thing); // logs 'exported thing', because that was exported from file 1
console.log(foo); // errors, because foo was created in another file
util.sayFoo(); // errors, because util was created in another file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment