Home > Net >  How do I make changes to a local variable without changing the global variable in javascript?
How do I make changes to a local variable without changing the global variable in javascript?

Time:06-28

var i = 100;

function gamePlay() {
       
    while(i >= 0) {
        if (i>0) {
            console.log(i);}
        else{console.log(**i 1**);}
        i--;
    }
}
    

When I increse i by 1 (the part of the code that is bold), I'd like to make that change occur locally. The rest of the code should use global i but the problem is that the change applies globally and the rest of the code stops working when I add 1 to i. This is the case even if I substract 1 before closing the while loop.

CodePudding user response:

Try this:

var i = 100;

function gamePlay() {
    let i2 = i; // local variable

    while(i2 >= 0) {
        if (i2 > 0) {
            console.log(i2);
        }
        else {
            console.log(i2 1);
        }

        i2--;
    }
}

CodePudding user response:

When you declare variables in a function they are local to that specific function but when you declare outside of the function they are global and can be used in any of the function. In your case var i = 100 is global and can be used in any function. so you need to declare another variable inside the while block.

CodePudding user response:

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitly by typing the var keyword before the name of the variable.

  • Related