While Loops in JavaScriptThe while loop in JavaScript is yet another type of control structure. For a review on what a control structure is, please see our last post on IF statements.

The main goal of the while loop is to continually re-run a specific chunk of code over and over again. This is very similar to the for loop with one important difference. Again, if you aren't familiar with the for loop, please review the topic here.

Let me take a minute to explain the difference between these two types of loops.

What's the Difference Between a WHILE Loop and a FOR Loop?

The difference between these two loops is how they decide to STOP looping.

You see, the for loop has a specific and predefined number of iterations that it will make. We know exactly how many times a for loop will iterate once the code is running and the JavaScript engine starts executing the for loop's code.

This is in stark contrast to the while loop. The while loop keeps looping while a specific condition is true. Once the condition evaluates to false then (and only then) will the while loop stop looping.

The reason why this is so different than the for loop is that we don't necessarily know when this condition will change from true to false, so we can't really guess how many iterations the while loop will make until it stops.

This is both a good thing and a bad thing.

Pros and Cons of the WHILE Loop

Let me start by addressing the only real “con” to the while loop.

It can run forever!

If you're in a situation where your while loop keeps looping to infinity, then your program is stuck (or frozen) and you'll need to shut down your browser to terminate the running JavaScript program. Not a very good user experience.

Having said that, an unruly while loop doesn't typically keep on running forever, because as good programmers we always make sure that our while loop's condition will at some point evaluate to false, right?

Right!

So the one rule you need to remember (and follow) is to always make sure that your condition will eventually evaluate to false.

Alright, having said that. The “pros” to using the while loop are quite abundant. Having a loop that will continually run until such time that a condition evaluates to false is very useful.

An example of a while loop in action would be asking a user for input again and again until they provide a valid input.

WHILE Loop Syntax

The syntax for the while loop is very straight forward.

You'll need to be sure to use the while keyword as well as defining the condition with which the loop will run. Also, like the other control structures, the while loop defines a scope.

Here's what the generic code looks like:

while ([condition(s)])
{
  // insert code to loop over here
}

Pretty simple right? The hardest part is to figure out what condition(s) you need to put in the while loop for it to function properly.

Remember that while the condition(s) is/are true, the loop will continue to run.

Cool, so now let's take a look at a real world example of the while loop.

WHILE Loop Example

Let's assume we want to prompt the user with a question. We want to ask them to enter a number between 1 and 10.

But what happens if they enter an incorrect value?

Well, we should ask them to enter the value again, and to be sure to abide by the restrictions (i.e. enter a number between 1 and 10).

This is where a for loop would fail miserably, because how are we supposed to know ahead of time how many times we should ask them for the input… right? We haven't a clue! So in comes the while loop to save the day.

Here's what that code could look like:

var theNumber = prompt("Please enter a number between 1 and 10.");

while (theNumber < 1 || theNumber > 10 || isNaN(theNumber))
{
  theNumber = prompt("Incorrect value entered, please enter a number between 1 and 10!");
}

alert("Great! You entered the number: " + theNumber);

What's interesting to note about the code example above is that we have three separate conditions in the while loop.

These three conditions are theNumber < 1 || theNumber > 10 || isNaN(theNumber). What this is saying is as follows:

  • IF theNumber is less than 1, OR
  • IF theNumber is greater than 10, OR
  • IF theNumber is NOT a number, then continue looping

So, because we're using the OR operator between each statement, this means that if ANY of the conditions are true, then the overall while loop's condition will evaluate to true, and thus it will continue to loop.

Only in the case that ALL three conditions are false, will the overall while loop's condition evaluate to false, and thus exit the loop.

So now, go ahead and try the code out for yourself!

In Summary

The while loop is actually the only real loop in modern day programming languages. The for loop is actually just a special kind of while loop.

This is the case because you can re-create a for loop using the while loop's syntax… watch and learn:

var counter = 0;

while (counter < 10)
{
  counter = counter + 1;
  console.log("The counter is currently at: " + counter);
}

As you can see, this code will run exactly 10 times, no more, no less. This is exactly the same functionality as a for loop.

Neat right?

So you shouldn't be afraid to use the while loop, because without it, there would be tons of applications out there that just wouldn't work properly at all!

I hope you enjoyed this tutorial, and if you did, be sure to put in your email address in the box below to get a free goodie delivered right to your inbox.

Free Java Roadmap

Discover exactly what you need to learn and where to start in order to become a professional coder.