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

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops `do ... while` Loops

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

do while loop

Is it necessary to iterate the loop at only true condition? It looks like here in the while loop condition that "Dave is forcly trying to make the codition true to iterate the loop". Why don't just he wrote

do{

}while(correctGuess === false )

Isn't it give the same result?

Mathew Tran
Mathew Tran
Courses Plus Student 10,205 Points

!correctGuess evaluates the same as correctGuess === false

It's really up to how you or your team likes to code.

Most people I see, like to use the !correctGuess version, it could mean the value is 0 or null

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

I can see both the method works.
But what i want to ask is , correctGuess has been set to false . And as soon as , the randomNumber matches the guess , correctGuess is changed to true. So isn't is easier to set the while loop condition as

while(correctGuess === false )

because it will change only when the randomNumber matches guess and in that case it will exit the loop. The only difference between mine and Dave code is that "I am iterating the loop at false value while Dave is iterating at true value of correctGuess.

1 Answer

Mathew Tran
PLUS
Mathew Tran
Courses Plus Student 10,205 Points

err I don't think I am understanding your question clearly enough.

To enter in a while loop, the condition must be true

I'll provide an example of what is occurring with both yours and Davids logic.

Let's say the answer is 1. But the user provides a 2
When using correctGuess === false, user repeats the loop
When using  ! correctGuess , user repeats the loop
User now provides a 1
When using correctGuess === false, user exits the loop
When using  ! correctGuess , user exits the loop