Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Andrew Reynolds
Front End Web Development Techdegree Graduate 23,333 PointsWhy won't my Do/while loop break?
do {
var word = prompt('what word am I thinking');
} while (word.toUpperCase() !== "HI" || word.toUpperCase() !== "BYE" );
I want it so that if someone types Hi or Bye that the loop ends. However the loop never ends. If I just use one of the conditions it breaks but when I use the || or operator and give another condition it just never ends.
Is it not possible to have 2 conditions for a do/while loop?
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! You're close, but yes, this is an infinite loop. Yes, you may have two conditions, but let's take a look at using the || and what happens with that logic. When you use the || only one of the conditions needs to be true for it to evaluate to true.
Here's what happens if I type in "Hello". It turns it to upper case and compares it to "HI". Because it is not equal to "HI", the whole condition automatically evaluates to true and the loop continues.
But what happens if I type in "hi"? It turns that in to "HI" and compares it to "HI". That is equal to "HI" so it fails the first condition and continues to the second condition. It is not equal to "BYE" so that part evaluates to true. Remember, only one has to be true for the whole thing to be true, and the loop continues.
The same thing happens for "bye". It turns that into "BYE" and compares it to "HI". They are not equal so the expression evaluates to true and the loop continues.
What you're wanting here is the && operator. The word needs to both be not "HI" and not "BYE". Replacing the || with the && will cause it to work as you're expecting.
Hope this helps!
Steven Parker
243,658 PointsYou just used the wrong logical operator. By testing "OR", then if either condition is true, then the loop continues. And no matter what you type, at least one of those words will not match.
So what you want is for the loop to continue only if they both don't match, which would require an "AND" operation ("&&").