0

this javascript code runs successfully but I think it doesn't make through its "else" statement since it doesn't print its console...why?

 i = 0;
    for(var i=1; i<4; i++) {
    var crazy = prompt("would you marry me?");
         if(crazy === "Yes"|| "yes") {
           console.log("hell ya!");
       }
     /* when it asks "will you marry me" and if the user says either "No" or      "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
     else if (crazy ==="No" ||"no") {
       console.log("ok..I'll try again next time !");
   }
}
var love = false;
do {
      console.log("nonetheless, I LOVE YOU !");
}
while(love);
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
Marie Mirbekian
  • 183
  • 1
  • 2
  • 9

3 Answers3

1

Try something like this,

 if(crazy.toUpperCase() === "YES") {
    console.log("hell ya!");
 }
Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
0

Try this..Nice piece of code though.. Is it a marriage proposal to some geeky guy?

i = 0;
    for(var i=1; i<4; i++) {
    var crazy = prompt("would you marry me?");
         if(crazy === "Yes"|| crazy ==="yes") {
           console.log("hell ya!");
       }
     /* when it asks "will you marry me" and if the user says either "No" or      "no", it does't print "ok..I'' try again next time". instead, it still says "hell ya !" */
     else if (crazy ==="No" ||crazy === "no") {
       console.log("ok..I'll try again next time !");
   }
}
var love = false;
do {
      console.log("nonetheless, I LOVE YOU !");
}
while(love);
prashant
  • 2,181
  • 2
  • 22
  • 37
  • hey thank you so much ! This is a lot of help..haha:)) No I don't have boyfriend but I thought maybe this can help some guys someday to make it less stressful and actually funny just by telling their girlfriend to enter their website and then Wow ! – Marie Mirbekian Apr 23 '15 at 01:55
0

Here’s the explanation:

crazy === "Yes" || "yes"

This statement does the following thing:

  1. It compares whether crazy is identical to the string "Yes"
  2. If they’re not identical, “use” "yes"

Put this into an if statement and you get this:

  • Execute everything in if block,
    1. …if crazy is identical to "Yes", or
    2. …if "yes".

What does "yes" by itself mean in an if statement? It is evaluated as true.

Every string that is not the empty string is evaluated as true and every empty string is evaluated as false. See the MDN articles on Boolean and falsy values.

You can verify this by typing doubly-negated expressions like these into the console:

!!"yes"; // true
!!"test"; // true
!!""; // false

What you need to do is a second comparison:

if(crazy === "Yes" || crazy === "yes")

and

else if(crazy === "No" || crazy === "no")

Alternative approaches include crazy.toLowerCase() === "yes" for only one comparison, or ["Yes", "yes"].includes(crazy).

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75