Search code examples
javascriptclosuresscope-chain

JavaScript Closure vs. Local


I have a Javascript main file that is enclosed by an immediately-called closure (so as not to pollute 'global':

(function () {
"use strict";
   var closureVariable = [];
...
}());

I made a simple, bone-headed coding error when removing a variable from a function header such that my code had a comma instead of a semicolon:

function fred () {
    var i,

    closureVariable = [1,2,3,4];
    confused();
}
function confused () {
    console.log(closureVariable);     // Prints '[]'
}

Certainly the missing semicolon on the 'var i' line was the problem. However the behavior I thought should happen is that my now locally-defined variable 'closureVariable' should have shadowed the higher-level scope definition, and the value of my locally-defined variable should have been available to functions lower down in the scope chain (that is, function 'confused' should have printed out '[1,2,3,4]';

What am I not understanding about Javascript scope chains here?


Solution

  • What you are expecting is known as dynamic scoping. This is a valid language design choice, though widely considered inferior today. It's just not what Javascript does. Like many popular languages, Javascript uses lexical scoping. That means confused's scope is not considered a child scope of fred's, because its definition is not inside the definition of fred. The fact that fred calls confused has no effect.