Skip to content Skip to sidebar Skip to footer

How To Change A Global Variable With An If/else Statement

I have this code where i want to change var n if the var thisRoll is not 'green', but i only get undefined in the output from console.log(n) var thisRoll = 'red' var n; var base_b

Solution 1:

Because your n is also a parameter in the function. So it hides the outer variable n in the function and when you access the n, it refers to the parameter variable. To work with the global n, you need to remove the parameter, or change it's name.

functionbetInput(thisRoll) {
    var x;
    if (thisRoll === 'green') {
        x = base_bet;
        n = 0;
    } else {
        n = n + 1;
    }
    return x;
}

Solution 2:

The function betInput(thisRoll, n) contains a parameter n which shadows the global variable n. Calling that function using betInput(thisRoll) merely sets the local n to a default value.

(The fact that Javascript is lax on this - and many other things - does make it difficult to write stable code in the language).

Simply remove n from the function parameter list and all will be well.

Solution 3:

Remove the parameter in your function. There's n there, which makes it scoped to the function.

functionbetInput(thisRoll, n) {
//------------------------^^^

Change your function to:

functionbetInput(thisRoll) {

So that, n will reference your global variable, otherwise n is undefined in your function scope

Post a Comment for "How To Change A Global Variable With An If/else Statement"