Gadrri
Gadrri

Reputation: 41

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

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.

Upvotes: 2

Views: 191

Answers (2)

Ashish Bali
Ashish Bali

Reputation: 1

When you declare variables in a function, they are local to that specific function. But when you declare them outside of the function, they are global and can be used anywhere.

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.

Upvotes: 0

Ar Rakin
Ar Rakin

Reputation: 542

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--;
    }
}

Upvotes: 1

Related Questions