JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Ernie Smith
Ernie Smith
8,511 Points

Confused about how the first computer guess is made to start the loop

In a while loop the code inside the code block does NOT run unless the condition is true . But when did the computer first make a wrong guess to test the condition?

It seems like var guess has no value (number) to test until guess = getRandomNumber (upper) is run? But/ so the code block should never start? This is what has me perplexed.

Basically to me it looks like the loop should never run because "guess" has no number to compare to the randomNumber. Why is a do loop not necessary? So confused.

2 Answers

Ronald Opara
Ronald Opara
Full Stack JavaScript Techdegree Student 3,201 Points

The variable 'guess' initially does not have any value when created. So, when you look at the beginning of the while loop you will see 'while ( guess !== randomNumber )'. What is located in the parenthesis is important. Although the variable 'guess' does not have a value, it is still NOT EQUAL TO (!==) randomNumber, which returns as true. In simplified terms, when 'guess' IS NOT equal to randomNumber the condition is true and the loop will run, but when guess IS equal to randomNumber the condition is false and the loop will stop. Whenever the condition is true inside of a while loop, the code inside the code block will run which is what you see inside this program.

It looks like in JavaScript that as long as you declare the variable within the scope of the loop then it's valid.

Other languages you would need to establish the variable before the condition statements.