Scope
// Scope
/* If you ask the phone store employee for a phone model that her store doesn't carry,
she will not be able to sell you the phone you want. She only has access to the phones
in her store's inventory. You'll have to try another store to see if you can find the
phone you're looking for.
Programming has a term for this concept: scope (technically called lexical scope). In
JavaScript, each function gets its own scope. Scope is basically a collection of variables
as well as the rules for how those variables are accessed by name. Only code inside that
function can access that function's scoped variables.
A variable name has to be unique within the same scope -- there can't be two different a
variables sitting right next to each other. But the same variable name a could appear in
different scopes. */
function one() {
// this `a` only belongs to the `one()` function
var a = 1;
console.log( a );
}
function two() {
// this `a` only belongs to the `two()` function
var a = 2;
console.log( a );
}
one(); // 1
two(); // 2
/* Also, a scope can be nested inside another scope, just like if a clown at a birthday
party blows up one balloon inside another balloon. If one scope is nested inside another,
code inside the innermost scope can access variables from either scope. */
function outer() {
var a = 1;
function inner() {
var b = 2;
// we can access both `a` and `b` here
console.log( a + b ); // 3
}
inner();
// we can only access `a` here
console.log( a ); // 1
}
outer();
/* Lexical scope rules say that code in one scope can access variables of either that
scope or any scope outside of it.
So, code inside the inner() function has access to both variables a and b, but code
in outer() has access only to a -- it cannot access b because that variable is only inside inner(). */