Skip to content

Instantly share code, notes, and snippets.

@adamki
Last active November 17, 2015 17:53
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 adamki/4b0d5bf6fbf7974839ab to your computer and use it in GitHub Desktop.
Save adamki/4b0d5bf6fbf7974839ab to your computer and use it in GitHub Desktop.
demo and explain JS scopes!
# Javascript Scopes
Javascript scopes are pretty confusing if you come from a Ruby BG. Many times, I _thought_ that I was saving data to a variable or passing a specific value, but in all reality, I was passing around nil. I would like to demonstrate some of the *GOTCHAS* of Js.
EXAMPLE ONE: Variables have local and global scopes. They work like so:
```
var test = "I'm global";
function testScope() {
test = "I'm local";
console.log(test);
}
console.log(test); // output: I'm global
testScope(); // output: I'm local
console.log(test); // output: I'm local (the global variable is reassigned
```
* demonstrate the code sample above and explain how scoping works with a basic JS function. Variables can only be seen from their scope. explain that we actually have TWO scopes going on in this sample
* In this example, the local "test" is over-riding the global "test" since it did not use the Key Word 'var'.
* Also, explain that the `test` var was literally re-assigned.
```
var locales = {
europe: function() { // The Europe continent's local scope
var myFriend = "Monique";
var france = function() { // The France country's local scope
var paris = function() { // The Paris city's local scope
console.log(myFriend);
};
paris();
};
france();
}
};
locales.europe();
```
Demonstrate that we have 3 scopes. Monique > Paris > France > Europe. Explain that the fact that Europe() calls France() which calls Paris(). This is Lexical Static Scoping.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment