Local vs Global variable BUG?


#1

var bool =true
var counter=0
var loop = function(){
while(bool)
{
counter++
if (counter==10)
{
bool= false
}
}
console.log(counter)
};
loop();
console.log(counter)

i get :

10
10

but if i change IF true block from bool=false -> var bool =false then i get :

0
0

How is that possible ??


#2

I'm not sure what answer you're expecting, but to me that's exactly what I'd expect the counter to get.

Remember, you're not reverting "counter" back to 0 after you do the loop, so every time the "counter" variable counts to ten, ends the loop, then posts the number it has, which is 10.

When you call the loop to go through, it doesn't change the number because the "if" statement sees that "counter" is already 10, and will post the console.log statement again.

HOWEVER, you're teetering dangerously on a endless loop, because if you call the "loop" twice, it'll reach the number "11" and will count up forever because it can never again be equal to "10".

Otherwise the bool or Boolean, is a true / false only, so "while(bool)" is the same as saying "while(bool == true)". If it's not true, or you change bool to false, then it will not run the loop, and the console.log statement will say "0" twice, since both console.log statements are outside of the while loop.

I know this is complicated, but you're simply overcomplicating it for yourself. So just take a step back and look at what you're trying to accomplish with this, and figure out what steps you need to get there.

I hope this helps! :+1:


#3

Ahh indeed i never thought about the danger of the infinite loop ! Thanks for saving me time from potentially huuge problems.

however, my initial problem was the difference in the results, between bool=false compared to var bool = false inside the IF statement. Each gives me different results . but i dont understand how it could possibly affect the counter variable.

bool=false gives me :
10
10
var bool = false gives me :
0
0

3 hours and still havent got a clue.


#4

that depends, because "bool=false" means the variable wasn't created and will give you an error,

"var bool = false" creates the variable and sets it equal to the value of false.


#5

ahh , hmm i have to go back and check variable scope once again ! thanks !