Jump to content

Why doesn't && operator work in a while loop?


Oladunni Faith

Recommended Posts

I tried to implement a rule that quits the operation on a todo project when I type 'q' or 'quit' in a while loop but it wont work with the logical OR operator || but works fine with the logical && operator. Can someone please Explain why as I'm new to Javascript and it was a code-along group project.

Code Below 👇

let message = prompt('Enter q or quit to quit this process!');
while (message !== 'q' || message !== 'quit'){
    prompt('Please Enter quit or q to quit this operation!');
}
alert('You quit the operation!');

It just continues the loop even when I type q or quit with my keyboard. I know the rules guiding the use of logical (&&) and (||) in a statement but this is a bit complicated for me to understand is why I'm here asking.... 

I'd really appreciate a very simple explanation to ease my understanding.

Link to comment
Share on other sites

With the || operator, the loop will continue running as long as any one of the two conditions is true. The !== operators are making things look more complicate than they really are.

I've separated the conditions from the loop to make it more clear what's happening:

let message = prompt('Enter q or quit to quit this process!');

let condition1 = message !== 'q';
let condition2 = message !== 'quit';

while (condition1 || condition2){
    // condition1 is true if the message is "quit"
    // condition2 is true if the message is "q"
    // No matter what value message has, at least one of the two conditions is true.
    // Therefore, the loop never stops.

    prompt('Please Enter quit or q to quit this operation!');
}
alert('You quit the operation!');

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...