0

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);
}
Martin Clemens Bloch
  • 1,047
  • 1
  • 12
  • 28

2 Answers2

1

In the two loop examples you've shown, your variables are not formally declared, so they become global by default.

for(H=1; H<5;H++){}
for(zzz = 0; zzz < 30; zzz++)

You are initializing H and zzz here, but not declaring H and zzz so, even though it's in a function, it becomes an implicit Global.

The code to explicitly declare it as local to the function would be:

for(var H=1; H<5;H++){}  // Function Scope
for(var zzz = 0; zzz < 30; zzz++)

or:

for(let H=1; H<5;H++){}  // Block Scope
for(let zzz = 0; zzz < 30; zzz++)

With testFunc, you are declaring an argument, called H so that becomes an implicit local variable for that function and it "hides" the Global H.

var testFunc = function(H){

Really, what you need to understand here is what's called the "scope chain", which I've also written about here.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

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);
Ben Stephens
  • 3,303
  • 1
  • 4
  • 8