Reputation: 17
var question=prompt("What is your 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 I enter age 14, it will display "Coupon 1" and then after it also displays "No Coupon". It does this for every if statement except the last one, age 50. If I enter age 50, I only get Coupon 4 and no "No Coupon". I do not understand why it does this.
Upvotes: 0
Views: 70
Reputation: 2745
Your if
statements are not connected, each one is happening independent of the others, which means all of the cases are being checked, even if an earlier one returns true
. Your code is more like this:
var question = prompt("What is your 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 it to use a string of if elseif
statements, which means the logic is one continuous flow:
var question = prompt("What is your 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 the above, no coupon
else {
alert("No Coupon");
}
Javascript - and many other languages - has a built in syntax that specifically handles this sort of if-elseif-else chain, called a Switch Statement. You can rewrite your code using a switch like this:
switch (prompt("What is your 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;
}
Upvotes: 1
Reputation: 1416
only the last if and else statements are connected, and the first three are three independent if statements, so each time for the first three cases one of the first conditions is true and the last else statement also is true.
var question=prompt("What is your age?");
if (question == 14) {
alert("Coupon 1")
}
else if (question == 21) {
alert("Coupon 2")
}
else if (question == 30) {
alert("Coupon 3")
}
else if (question == 50){
alert ("Coupon 4")
}
else {
alert("No Coupon")
}
read about if-else if-else statements here
Upvotes: 0