Skip to content
Advertisement

Change value of a variable inside foreach loop? Make it available outside the loop

I’m setting an initial flag then doing a foreach which changes the flag to a different value but outside the foreach loop I still see the original flag. As if nothing changed. But it did change inside the foreach loop

The value is only changed inside the foreach loop, but not outside of it..

I saw a number of similar questions but they all deal with the actual array values, in this case it’s a simple variable outside of the foreach loop.

    var arr = ["one"];

    var str = 0;

    arr.forEach(function(part){

        if(part == 'one') {
            var str = 1;
            console.log('str changed to: ' + str);
        }

    })

    console.log('str is now: ' + str);

This will return

str changed to: 1
str is now: 0

Based on my PHP logic above should return “str is now: 1“, why does it have the original value of 0?

Advertisement

Answer

This is because you are re-declaring the variable with var in the loop instead of just updating/setting it. Re-declaring it wipes out the earlier variable of the same name from the previous loop iteration and hides the one from the function in the higher scope. It establishes a new one instead of just updating the value in the existing one.

var arr = ["one"];
var str = 0;
arr.forEach(function(part){
 if(part == 'one') {
   str = 1;
   console.log('str changed to: ' + str);
 }
})

console.log('str is now: ' + str);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement