Grayson McMurry
Grayson McMurry

Reputation: 11

Javascript if/else statements help, what am i doing wrong with this code?

The following code is from my course and I can't get it to work.

I've tried putting everything possible that i can think of

var eatSteak = confirm("Do you eat steak?");
var confirmSteak = confirm("You like Steak!");
var confirmNoSteak = confirm("Here's a tofu stir-fry");
var howOld = prompt("How old are you?");
var howNotOld = confirm("No Sake for you!");
var sakeForYou = confirm("Sake for you!");
var tryAgain = confirm("TRY AGAIN!");
if (eatSteak == true) {
  alert(confirmSteak);
} else {
  alert(confirmNoSteak);
}
if (howOld < 21) {
  alert(howNotOld);
} else if (howOld >= 21) {
  alert(sakeForYou);
} else {
  alert(tryAgain);
}

No error messages displayed by console

Upvotes: 0

Views: 55

Answers (2)

Charlie
Charlie

Reputation: 23818

One simple rule. Use prompt and confirm only when you want to get a user input.

if (confirm("Do you eat steak?") == true) 
   alert('You like Steak!')
else 
   alert('Heres a tofu stir-fry');



//Here is a variable which stores the user input
var age = prompt("How old are you?");

if (age < 21)
  alert('No Sake for you!')  
else 
  if (age > 21) 
    alert('Sake for you!')  
  else 
    alert('TRY AGAIN!');

Upvotes: 0

Barmar
Barmar

Reputation: 781706

confirm() should only be used to ask a question. If you just want to set a variable to a message, you shouldn't call confirm(). So statements like

var confirmSteak = confirm("You like Steak!");

should just be

var confirmSteak = "You like Steak!";

Also, when you're testing howOld, you check if they're less than 21, then check if they're at least 21. Those are the only two possibilities, it can never get to the last else block. So you can just use if and else -- either they get sake or not.

var eatSteak = confirm("Do you eat steak?");
var confirmSteak = "You like Steak!";
var confirmNoSteak = "Here's a tofu stir-fry";
var howOld = prompt("How old are you?");
var howNotOld = "No Sake for you!";
var sakeForYou = "Sake for you!";
if (eatSteak == true) {
  alert(confirmSteak);
} else {
  alert(confirmNoSteak);
}
if (howOld < 21) {
  alert(howNotOld);
} else  {
  alert(sakeForYou);
}

Upvotes: 1

Related Questions