0

Basically no matter what I enter when I call the function it says you have fled. I may just be overlooking something but I can't figure out what.

    function attack() {
var battle = prompt("Attack of Flee?")
if (battle === "Flee" || "flee") {
    alert("You have fled");
    } 
else if (battle === "Attack" || "attack"){
    alert("You have attacked");
}   
    }
  • `battle === "Flee" || "flee"` won't work as you expect. It will compare `battle === "Flee"` (which may or may not be `true`), and then check the truthyness of `"flee"`, which is always `true`. You have to compare `battle` against something each time. Use `battle === "Flee" || battle === "flee"` (and similar for the other comparison). Although I'd suggest just setting the `prompt`'s value to lowercase, and comparing that – Ian Apr 12 '14 at 05:03
  • what error does this code throws?? Can you specify the situation? – Misters Apr 12 '14 at 05:04
  • @Misters: The code doesn't throw an error. – Felix Kling Apr 12 '14 at 05:13
  • `"flee"` is always true, also just force the case using either `toUpperCase()` or `toLowerCase()`. Then we need to only check a single value, no matter how the user typed in there string (case-wise), it will work. – Spencer Wieczorek Apr 12 '14 at 05:16
  • [javascript - Check variable equality against a list of values - Stack Overflow](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) – user202729 Jul 30 '18 at 06:51
  • Possible duplicate of [Or operator not working in IF statement Node.js](https://stackoverflow.com/questions/33089632/or-operator-not-working-in-if-statement-node-js) – user202729 Jul 30 '18 at 06:58

3 Answers3

2

Try if (battle === "Flee" || battle === "flee") The right hand side is just evaluating the string "flee" for truthiness, which always evaluates true.

cryocide
  • 691
  • 5
  • 11
  • The other answers are great! Actually going to do those instead but this one actually did clear the immediate problem. – user3525956 Apr 12 '14 at 20:08
2
  1. if (battle === "Flee" || "flee") in this if condition you should write

    if (battle === "Flee" || battle === "flee")

if you want to ignore case then batter if u change string to lower case here is example

function attack() {
    var battle = prompt("Attack of Flee?");
    if (battle.toLowerCase() === "flee") {
        alert("You have fled");
    } else if (battle.toLowerCase() === "attack") {
        alert("You have attacked");
    }
}
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
0

Try:

function attack() {
    var battle = prompt("Attack of Flee?");
    var ActionTaken = "";
    if (battle.ToLowerCase() == "flee") {
        ActionTaken = "You have fled";
    } 
    else if (battle.ToLowerCase() == "attack") {
        ActionTaken = "You have attacked";
    }
    alert(ActionTaken);
}
DoctorLouie
  • 2,699
  • 1
  • 18
  • 23