Search code examples
javascriptfor-loopwebscopeglobal-variables

Is this a scope error/leak in the JavaScript for-loop implementation of my browser or my misunderstanding?


If I run the code below it acts as expected. (Expected being that both normal code languages AND JavaScript have "local scope" in functions) Thus the variable is not changed by the sub function.

testFunc(0);

var bFunc = function(){
    for(H=1; H<5;H++){}
    alert("bFunc H:"+H);
};
var testFunc = function(H){
    alert("CallId 1, H: " + H);
    bFunc();
    alert("CallId 2, H: " + H);
};

When running the code below it fails with the variable being modified inside the sub function:

forFunc();

var cFunc = function(){
    for(zzz = 0; zzz < 30; zzz++)
    {}
}
var forFunc = function(){
    for(zzz = 0; zzz < 5; zzz++){
        alert("zzz:"+zzz);
        cFunc();
    }
    alert("Scope leak if not 5:"+zzz);
}

Solution

  • In your first bit of code the H in bFunc is a global variable. The H in testFunc is not because it's an argument to the function. The zzz in your second example is always in global scope. let const and var can be used to control variable scope.

    var bFunc = function(){
        for(H=1; H<5;H++){}
    };
    var testFunc = function(H){
        console.log("CallId 1, window.H: " + window.H);
        bFunc();
        console.log("CallId 2, window.H: " + window.H);
    };
    
    testFunc(0);

    var bFunc = function(){
        for(let J=1; J<5;J++){}
    };
    var testFunc = function(J){
        console.log("CallId 1, window.J: " + window.J);
        bFunc();
        console.log("CallId 2, window.J: " + window.J);
    };
    
    testFunc(0);