Skip to content

Instantly share code, notes, and snippets.

@aweary
Last active January 10, 2016 00:59
Show Gist options
  • Save aweary/d3e2ab5130b776d76937 to your computer and use it in GitHub Desktop.
Save aweary/d3e2ab5130b776d76937 to your computer and use it in GitHub Desktop.
/*
A scope is basically the context in which a variable is accesible. There are two types of scopes in JS: global and local.
The global scope is the topmost scope. You create local scopes with funcitons. Variables declared within funcitons
are "scoped" to that function, and those variables are only accessible to scopes that are children of that scope.
Think of them as nested containers.
*/
// This variable is within the global scope since its not declared within and function.
var global = "I am global!"
/*
Scopes are created with functions. If you declare a variable within a funciton, then that variable is only accessible to
scopes WITHIN that scope. Since scopes are nested, you can access global variables--or variables declared within parent scopes-- as well
Since all scopes are by definition children of the global scope, global variables are accessible anywhere in the program.
*/
// This function declares a variable `firstLocal`. It also has access to the `global` variable since its in a parent scope (the global scope).
function someFunction() {
var firstLocal = 'I am a local variable to someFunction'
return firstLocal + global;
}
// If we try to access firstLocal outside of `someFunction` we will get an error, since its not within the current scope, or a parent scope.
console.log(firstLocal)
// Uncaught ReferenceError: firstLocal is not defined(…)
// This function is also throw an error since its trying to access `firstLocal`, which is in the scope of `someFunction`
// and `someFunction` is sibling of `someOtherFunction` not a parent
function someOtherFunction() {
var secondLocal = 'I am also a local variable';
return firstLocal + secondLocal + global;
// Uncaught ReferenceError: firstLocal is not defined(…)
}
function anotherFunction() {
var thirdLocal = 'Im another local!'
// This WILL work since `thirdLocal` is declared within the parent function/scope `anotherFunction`
// and `global` is also a parent (not a direct parent, but a parent of a parent, which is still a parent).
function aChildFunction() {
console.log(thirdLocal + global)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment