Cuckoo Cuckoo - 3 months ago 9
Javascript Question

Confusion using parenthesis with and or

I'm new to Javascript, but in my head the below statement should be false if I don't type 'yes' or 'no'. However, the script seems to be ignoring this, and just returning true or false depending on whether a=1 or not. Can someone exlain what I'm doing wrong? Many thanks in advance.



var a = 1;
var box1 = prompt("Type 'yes' or 'no' for statement to be true");
if ((box1 === "yes" || "no") && a === 1) {
alert("Hooray!");
}




Answer

You need to change your condition to:

(box1 === "yes" || box1 === "no")

Your condition is evaluation to: box1 equals "yes", or "no". Any string that is not an empty string is evaluated to true so "no" is converted to true which means your condition always evaluates to true.

var a = 1;
var box1 = prompt("Type 'yes' or 'no' for statement to be true");
if ((box1 === "yes" || box1 === "no") && a === 1) {
  alert("Hooray!");
}