javascript - else statement not working correctly -
var question=prompt("what age?"); if (question == 14) { alert("coupon 1") } if (question == 21) { alert("coupon 2") } if (question == 30) { alert("coupon 3") } if (question == 50){ alert ("coupon 4") } else { alert("no coupon") }
if enter age 14, display "coupon 1" , after displays "no coupon". every if statement except last one, age 50. if enter age 50, coupon 4 , no "no coupon". not understand why this.
your if
statements not connected, each 1 happening independent of others, means of cases being checked, if earlier 1 returns true
. code more this:
var question = prompt("what age?"); //check if 14 if (question == 14) { alert("coupon 1") } //check if 21 if (question == 21) { alert("coupon 2") } //check if 30 if (question == 30) { alert("coupon 3") } //check if 50, else no coupon if (question == 50){ alert ("coupon 4") } else { alert("no coupon") }
try changing use string of if elseif
statements, means logic 1 continuous flow:
var question = prompt("what age?"); //check if 14 if (question == 14) { alert("coupon 1") } //check if 21 else if (question == 21) { alert("coupon 2") } //check if 30 else if (question == 30) { alert("coupon 3") } //check if 50 else if (question == 50){ alert ("coupon 4") } //if none of above, no coupon else { alert("no coupon"); }
javascript - , many other languages - has built in syntax handles sort of if-elseif-else chain, called switch statement. can rewrite code using switch this:
switch (prompt("what age?")) { case 14: alert("coupon 1"); break; case 21: alert("coupon 2"); break; case 30: alert("coupon 3"); break; case 50: alert("coupon 4"); break; default: alert("no coupon"); break; }
Comments
Post a Comment