Scope

by Joshua McNeese

JavaScript

// Variables declared in global scope (Window)
var x = 5;
y = 10;

// Objects are no different
// It's all global here
var myObj = {
    name: "Mr. Object",
    x: x // i can access variables in my scope
}

// Typical blocks do not affect scope
if (x<10) {
    // z becomes global
    // x is in my scope
     var z = 20 + x;
}

console.group("From global");
console.log("x:", x);
console.log("y:",y);
console.log("myObj:",myObj);
console.groupEnd();

// Only a function defines a new scope
function foo(fooVar) {
    
    // the "x" here is in this function's scope, not global
    // there now exists two "x" variables in this program (shadowed)
    var x = 222;   
    
    // I cannot access Function bar's barVar from here
    console.group("From foo");
    console.log("x:",x);
    //console.log(barVar); // ReferenceError
    console.log("y:",y);
    console.groupEnd();
    
    function bar(barVar) {
        
        // But from here I can access everything 
        // below me in the scope chain
        // (Except shadowed variables)
        
        console.group("From bar");
        console.log("barVar:",barVar); // from my scope
        console.log("fooVar:",fooVar); // from my parent scope, foo's scope
        console.log("x:",x); // shadowed in foo's scope
        console.log("y:",y); // from global scope
        console.groupEnd();
        
    }
    
    bar("Mr. Bar");
    
}

foo("Mr. Foo");