Jaakko Uusitalo Jaakko Uusitalo - 3 months ago 6
Javascript Question

Two same variables with different values in If and else statement

Should I just change payback and payback to payback1 and payback2 ? Or is there better way to do it?

function play() {
var bet = document.getElementById("bet").value;
var pips = Math.round((Math.random()*5)+1);

if(pips == 1|| pips == 3 || pips == 5){
document.getElementById("answer").innerHTML = "No pay";
}
else if(pips == 2|| pips == 4) {
var payback = 1.25*bet;
document.getElementById("answer").innerHTML = "You'll receive: "+payback;

}
else {
var payback = 1.50*bet;
document.getElementById("answer").innerHTML = "You'll receive: "+payback;
}
}


Line 15: 'payback' is already defined.

I seriously tried coming up with a sensible title...

Answer

You can just declare it at the beginning and then modify it on your if/else:

function play() {
var bet = document.getElementById("bet").value;
var pips = Math.round((Math.random()*5)+1);
var payback;

if(pips == 1|| pips == 3 || pips == 5){
  document.getElementById("answer").innerHTML = "No pay";
}
else if(pips == 2|| pips == 4) {
  payback = 1.25*bet;
  document.getElementById("answer").innerHTML = "You'll receive: "+bet;

}
else {
  payback = 1.50*bet;
  document.getElementById("answer").innerHTML = "You'll receive: "+bet;
}

}