30 Days Of JavaScript

Day 4: Loops

Lesson 2: While

while loops are the unpopular and rarely used cousin to for loops. Conceptually they are:

1while a condition is true:
2do this

In real code that would be:

1let age = 30;
3while (age < 100) {
4  console.log("Still living!");

The problem with while loops is they are great at setting up infinite loops. The code above is an infinite loop, age never changes so will always be less than 100. A more realistic version of the above would be:

Unlike a for loop we have to manually decide where to put our loop condition change code (age = age + 5;). You can recreate a for loop with a while loop.

While it does the same, the for loop has a better structured syntax and as a result is the go to option between the two.

The main place a while loop would be used, is when you want an infinite loop ... Or near infinite at least. Most of a game runs in a while loop, each frame is one iteration of the loop and the code that's executed changes based on user input.

Something like this is not uncommon:

1let exit = false;
3while (exit === false) {
4  // doing game stuff
6  if (userInput === "exit button") {
7    exit = true;
8  }
11exit(); //this line is not real JavaScript code

When the user presses the exit button this is detected, the exit flag is set to true, so the exit === false is no longer true and the loop ends. The exit() line is hit and the game ends.

In 15 years of coding, I can probably count on 2 hands the number of times I've used a while loop. Focus on getting your head around for loops.

Speaking of for loops, we've got one more flavour to look at.


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co