Coding for Kids

Loops: While

All loops allow a computer to repeat a set of actions over a certain duration. The type of duration is different for each type of loop, depending on your program's needs.

A while loop is best used when you don't know how many times to you need to run a loop. You keep running it endlessly until a condition changes. What condition? That's up to you to decide and control.

Declaring a while loop

Use the keyword while and include a condition, like you do in an if statement. As long as the condition is true, the loop will keep running. Whatever code you want to have repeating over and over, put inside a code block with curly braces {}.

Syntax:

Example 1:

The following code will print the numbers 0 through 9 to the console.

  • let counter = 0;
  •  
  • while (counter < 10)
  • {
    • console.log(counter);
    • counter++;
  • }
See this in repl.it

Here what's happening:

  1. First, set a counter to zero; that's the initializer
  2. The while loop begins
    • Check to see if counter is less than 10
      • Yes, if counter is 0-9, run the code block
      • No, if counter equals 10 or more, exit the loop
    • The code block runs
      • Print the number to the console
      • Increase the count of counter by one with counter++
    • Return to the top of the loop
Coding for Kids

In a case like this, a for loop is actually better to use because this is just counting up to 10. But it's a good way to see the syntax in use.

Example 2:

Here's a more likely situation for a while loop.

We are in a boat and it has a leak. Oh no! We have to keep bailing out the water until we make it to shore.

  • let weHaveFurtherToGo = true;
  •  
  • while (weHaveFurtherToGo)
  • {
    • grabThePail();
    • scoopOutWater();
    •  
    • //this tells us how far we are away from shore after paddling
    • let distance = paddleTowardShore();
    •  
    • //we reset the value of weHaveFurtherToGo based on the distance
    • weHaveFurtherToGo = (distance > 0);
  • }
See this in repl.it
Coding for Kids

We don't know how many times we need to paddle before getting to shore, so a while loop is perfect. The loop will keep running until there's no more distance left to travel.

Infinite loop

What happens if the condition is never false? You end up with an infinite loop. It runs forever. Your computer or browser could crash, though some will recognize the infinite loop and offer for you to break out of it. But don't count on that. Always plan your loops carefully!

Infinite Loop Example 1:

Infinite Loop Example 2:

Infinite Loop Example 3:

You can use any true/false condition testing for the while loop, even a function call. But again, make sure there's a way for it to be false.

Are infinite loops always bad?

Nope! There are times they're very useful. Your browser runs in an infinite loop. As long as the browser is open, it keeps looping, checking for clicks on a page, for you scrolling, for a page loading, for any ads or videos or apps running, and so on. If there wasn't an infinite loop, these things would stop updating at some point. The only time that loop closes is when you close the browser, which really means, you stop running the entire program!

Essentially every smart device that's just on and waiting for you is running in such a loop, from your PlayStation to your computer to your iPad to your smart phone.

What if the loop condition starts false?

What happens if you get to a while loop and the starting condition is already false?

See this in repl.it

The loop itself is fine. After eating something, iAmHungry could be set to false, depending on how the function is written.

The problem is that the variable iAmHungry starts off as false.

Therefore, when it hits that first line of while, the condition is false right away and so the loop never runs, not even once.

Use do...while

If you start the loop with the keyword do and move the while (condition) to the end, you will ensure that the loop runs at least once.

Example:

Run this a few times.

  • let randomNumber; //undefined
  • do
  • {
    • console.log(randomNumber);
    • randomNumber = Math.random() * 100; //picks 0-100
  • } while (randomNumber < 90);
  •  
  • console.log("This is the value that ended the loop:");
  • console.log(randomNumber);
See this in repl.it
example do...while loop

The first time randomNumber is printed to the console, it says undefined. That's because we declared it, but didn't give it a value. The line with Math.random() gives the variable a number. That number is tested at the end of the loop. If it's less than 90, the loop goes again.

This loop is set up to display the value of randomNumber before a new number is chosen. Therefore, we won't see the value that breaks out of the loop. That's why we added the last line, so we can see it. If you want, you can also go into the console after running the program and type the variable name to see its result.

While you're learning all this, your brain is getting stronger!

—Dr. Wolf