0

I would like to print "Error" message every time a word is not found in a variable from prompt input, it does work with single comparison like for example if (variable!== "word"). But whenever i try to compare multiple words that are defined in the if statement with (variable!= "word1" || variable! != "word2") it returns true even if the word is "word1" or "word2".

var input = prompt ('Enter a string: "word1", "word2" or "word3"?');

if(input!== "word1" || input!=="word2" ||input!== "word3"){
    console.log("Error");
}
else{
//do some functions
};
  • 1
    Does this answer your question? [JavaScript: Simple way to check if variable is equal to two or more values?](https://stackoverflow.com/questions/12116326/javascript-simple-way-to-check-if-variable-is-equal-to-two-or-more-values) – Heretic Monkey Dec 12 '19 at 22:38
  • The logical OR (`||`) returns true if either side of the operator is true. If `input` is `"word1"` then `input!== "word1"` will be `false`, but `input!=="word2"` will be true, and vice versa. One of them is _always_ true and therefore the logical OR will always be `true`. – Ivar Dec 12 '19 at 22:38
  • @Doc_Balthazar can you please check does my answer resolves your use-case? If having any questions - feel free to provide feedback. Thanks! – Jordan Enev Dec 13 '19 at 10:52

3 Answers3

2

This is what you're looking for:

if ( !['word1', 'word2', 'word3'].includes(input)) console.log("Error");

If the input is not part of the array (correct answers), then the Error will be logged.

Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
1

Your specific error is because of using || (OR) instead of && (AND).

You want to ask "if the input isn't "word1" AND it also isn't "word2" AND it also isn't "word3"", and you can write the condition exactly like that. When you use OR, the if statement will always be true since the input can't be all 3 values at once.

Either way, I agree with Jordan that you ought to use an array.includes() for checking against many valid inputs.

Klaycon
  • 10,599
  • 18
  • 35
0

You can use indexOf with an array containing the words.

const searchArray = ["word1","word2","word3"];
if(searchArray.indexOf(input) == -1){console.log("Error")};
B. Ma
  • 221
  • 2
  • 15