2

Trying to create a black jack simulator via Javascript as an exercise to increase my JS accumen (started coding a few weeks ago).

To try and make it simple and self contained (within JS, no html) I've tried to use a prompt to simulate action and response.

function action(){
    var response = prompt("What would you like to do \nInput 1 for Draw Card \nInput 2 for Play hand");
    if(response !== 1 || response !== 2){
        action();
    }
}

So, my question is, why does this continue to repeat itself when I enter 1 or 2. I would assume nothing should happen if either 1 or 2 are entered. I thought maybe this is because the prompt is saving the variable as a string, and so I changed the 1 and 2 to "1" and "2", but this did not fix the problem. I'm sure I'm missing something very simple. Any help would be great.

Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
Joseph Erickson
  • 938
  • 3
  • 8
  • 24

2 Answers2

3

Your logic is wrong. "1" matches because it's different than "2", "2" matches because it's different than "1" and others match because they are different than "1" and "2".

Instead, you should use the AND operator:

response !== "1" && response !== "2"
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

Result of the prompt function is always a String, and strict comparison === of the String and Number types will of course yield false:

"1" === 1 // false
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Like I said in my question above, I tried using the following: if(response !== "1" || response !== "2"){ – Joseph Erickson Jan 08 '16 at 07:56
  • @JosephErickson `!==` is a strict equality, and `!=` is a loose equality operators. You are just negating them, but they are still strict, so: `response !== "1"` is the same as `!(response === "1")`. – dfsq Jan 08 '16 at 07:57
  • This has nothing to do with the type of comparison, the problem is his logic. – Barmar Jan 08 '16 at 09:35
  • @Barmar Of course it has. It's the half of the problem. The second part is the logic, agree. But without correct comparison it will not work too. – dfsq Jan 08 '16 at 09:53