Assignment021
While Loops
Another useful programming structure is the while loop.
You guessed my name!
- The while loop requires one parameter, just the condition.
- The condition is used to determine how many times to run the loop. The loop will continue to run while the condition is true. Once the condition is no longer true, the next line of JavaScript code will execute.
- The while loop will only run if the condition is true.
<script language="Javascript" type="text/javascript">
//declare the name variable
var name;
//set value of name variable
name = "Doodle Bug";
//declare the guess variable
var guess;
//create a prompt loop
//keep looping until the user guesses the correct name
while (guess != name)
{
guess = window.prompt("Guess my name!", "");
}
document.write("You guessed my name!");
</script>
The for loop and the while loop are essentially the same. However, the while loop doesn't have to use variables to count. Intstead it keeps running until a condition is no longer true.
The correct answer is: Doodle Bug