Jacob Hayslett Jacob Hayslett - 6 months ago 9
Javascript Question

!= operator not working in while loop condition when combined with || OR

I have a basic do while loop where I am executing a prompt's input value, then running it through the condition. For some odd reason when I use !== along with || in the same condition it does not work. I know that I can add additional parameters for it to compare against using isNaN and other logical operators, but it makes no sense why this does not work and I would like to get this route working.

var number;
do {
number = parseInt(prompt('Enter 1 or 2'));
}
while ((number !== 1) || (number !== 2));


If I were to run the following code with a single expression to compare against, it work no problem, but in the previous statement it does not like have multiple conditions to compare against.

var number;
do {
number = parseInt(prompt('Enter 1 or 2'));
}
while (number !== 1);


Thanks!

Answer

If the number is 1, then the LHS is false but it isn't 2 so the RHS is true and the overall test is true.

If the number is not 1, then the LHS is true and the overall test is true.

You need && there so you are saying If the number is not 1 and it is also not 2.

Comments