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_bet = 1;
function betInput(thisRoll, n) {
var x;
if (thisRoll === 'green') {
x = base_bet;
n = 0;
} else {
n = n + 1;
}
return x;
}
var X = betInput(thisRoll);
console.log(X);
console.log(n);
Shouldn't it add 1
when the thisRoll
aren't 'green'
?
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_bet = 1;
function betInput(thisRoll, n) {
var x;
if (thisRoll === 'green') {
x = base_bet;
n = 0;
} else {
n = n + 1;
}
return x;
}
var X = betInput(thisRoll);
console.log(X);
console.log(n);
Shouldn't it add 1
when the thisRoll
aren't 'green'
?
3 Answers
Reset to default 7Because 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.
function betInput(thisRoll) {
var x;
if (thisRoll === 'green') {
x = base_bet;
n = 0;
} else {
n = n + 1;
}
return x;
}
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.
Remove the parameter in your function. There's n
there, which makes it scoped to the function.
function betInput(thisRoll, n) {
//------------------------^^^
Change your function to:
function betInput(thisRoll) {
So that, n
will reference your global variable, otherwise n
is undefined in your function scope