Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement in javascript always true

So, I have the code, its not done, but all i want it to do is display one alert box if I write the word 'help', and say something else if anything else is entered.

function prompter() {
var reply = prompt("This script is made to help you learn about new bands, to view more info, type help, otherwise, just click OK") 
if (reply === 'help' || 'Help')
  {
  alert("This script helps you find new bands. It was originally written in Python 3.0.1, using Komodo IDE, but was then manually translated into Javascript. Please answer the questions honestly. If you have no opinion on a question, merely press OK without typing anything.")
  }
else
  {
  alert("Press OK to continue")
  }
};

but, what happens, is no matter what, the first alert box pops up, even if you press cancel! How should I fix this???

like image 310
Billjk Avatar asked Feb 15 '12 23:02

Billjk


People also ask

Why [] == [] is false in JavaScript?

Because [] creates a new array, so you are comparing one array object with another array object. It's not the contents of the arrays that is compared, the object references are compared. They are not equal because it's not the same object instance.

What is if true in JavaScript?

In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


2 Answers

if (reply === 'help' || 'Help')

should be:

if (reply === 'help' || reply === 'Help')

since 'Help' is "truthy" and so the first part of the if will always be entered.

Of course, even better would be to do a case-insensitive comparison:

if (reply.toLowerCase() === 'help')

Example: http://jsfiddle.net/qvEPe/

like image 116
Andrew Whitaker Avatar answered Sep 21 '22 00:09

Andrew Whitaker


The problem is here:

if (reply === 'help' || 'Help') // <-- 'Help' evaluates to TRUE
                                //      so condition is always TRUE

The equality operator doesn't "distribute", try

if (reply === 'help' || reply === 'Help')
like image 28
calebds Avatar answered Sep 21 '22 00:09

calebds