Local and global variable in while loop


#1




please see the line 6 for the question
Why if i use "var swag = false", it behaves incorrectly?
while "swag = false" is fine


var swag = true;

var soloLoop = function(){
    while(swag === true) {
        console.log("Looped once!");
        var swag = false; //!!!!!! if i use "swag = false", it behaves correctly, why?
    }
};

soloLoop()


#2

It behaves correctly because without that, it will never stop.

If you don't set swag to false, then swag will always be true.

That is called an infinite loop.


#3

sorry, i didnt make it clearly:
var swag = false; --> behave incorrectly --> nothing printed
sway = false; --> behave correctly

thanks


#4

Inside your function swag is undefined.so your loop will not run.
why undefined?
in javascript you can refer to a variable declared later, without getting an exception. This concept is known as hoisting.variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement.

var swag = true;

var soloLoop = function(){
   console.log(typeof swag) //swag is now undefined
    while(swag === true) {  
        console.log("Looped once!");
        var swag = false; 
    }
};

soloLoop()

is implicitly understood as:

var swag = true;
var soloLoop = function(){
var swag = false; //swag is undifined.This concept is known as hoisting
    while(condition){ 
        console.log("Looped once!");
    }
};

variables that are hoisted will return a value of undefined.

so simply remove the var keyword


#5

no.its not.
you can see what i said :slight_smile:


#6

thanks!! it is a new concept to me :heart:


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.