TOC

The community is working on translating this tutorial into Uzbek, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Control structures:

Loops: for and while

We just learned about if-statements, a very integral part of a programming language. Almost equally important are loops: The ability to iterate over the same block of code multiple times, with the possibility of directly controlling the number of iterations.

In JavaScript, there are currently two types of loop structures: The "for" loop and the "while" loop. They both come in several variations, and in this article we'll dig deeper into how they work and how you can use them.

The while loop

The simplest type of loop to get started with is the while loop. It has a very simple syntax:

while(somethingIsTrue) 
{
	DoStuff();
}

So, as long as the condition within the parentheses evaluates to true, the following block of code is repeated again and again. This requires you to do something within the repeated block which will allow the interpreter to exit the loop - otherwise, you will have created a so-called endless loop, which will prevent your code from ever finishing!

A real life example of a while loop could look like this:

let counter = 1;
while(counter <= 10)
{
	document.write(counter);
	counter = counter + 1;
}

It will run as long as the "counter" variable is not greater than 10, and for each iteration, we output the number AND increment the counter variable. Especially that last part is important, because without it, "counter" would never be greater than 10 and the loop would run endlessly. Also, as you will see later on, a "for" loop is actually a better match for a task like this one, but I needed a simple, straight-forward example to illustrate how a while loop works.

The do..while variant

With a regular while loop, as the in the example above, the condition is evaluated before entering the loop. This means that we may actually never enter it - if the condition is never true, the following block of code is never executed. If you want to see this for yourself, simply change the initial value of the "counter" variable in the above example to 11 and run it again!

The do..while variant of the while loop turns things upside down - instead of evaluating the condition prior to running the code, it does the evaluation AFTER the loop code has been executed. This ensures at least one iteration, which can be useful in some scenarios. Here's an example - notice how the while-part has been moved, clearly indicating the order in which things are done:

let counter = 11;
do
{
	document.write(counter);
	counter = counter + 1;
} while(counter <= 10);

In this example, I changed the while loop into a do..while loop, and then I changed the initial value of the counter variable to 11. If this had been a regular while loop, the code inside it would never have been executed, but because it's a do..while loop, the condition, which we have ensured will evaluate to false, is evaluated AFTER the first iteration, thereby ensuring at least one execution.

The for loop

A great alternative to the while loop is the for loop. It looks a bit more complicated, but that's because it's more flexible and therefore also used more frequently. The for loop works by declaring a counter, then a condition for this counter and then a step for the counter (increase or decrease) on each iteration, all specified into a single line - this is why it looks complicated. Allow me to illustrate with an example:

for(let counter = 1; counter <= 10; counter = counter + 1)
	document.write(counter);

Here we do pretty much the same thing we did with the first while loop: We count from 1 to 10. But as you can see, it requires less code, because the counter mechanism is basically built into the for loop. On the first line, we instruct the interpreter to do the following, with each instruction separated by a semicolon:

  • We declare a variable called counter and assign the value 1 to it
  • We specify that this loop must run as long as the counter variable is less-than-or-equal-to 10
  • We specify that on each iteration, the counter variable should be increased by one

I'm being intentionally verbose in this example, by using a long variable name and not using the increment operator (more on that one later on). A more real-life example would look like this:

for(let i = 1; i <= 10; i++)
	document.write(i);

Pretty cool how much we can accomplish with so little code, right?

Notice that this example of a for loop is extremely similar to our while loop from before. This is also because the for loop is not executed in the exact sequence as the code might imply. You might expect that all three parts of the first line is executed first, and then the actual code of the loop, but that's not the case. Instead, the for loop is processed like this:

  1. The variable is declared
  2. The condition is checked, meaning that if the condition fails on the first try, no iterations are ever made
  3. If the condition succeeds, the loop code (in this case, our document.write()) is executed
  4. The step (i++), last part of the loop, is executed

This might seem a bit confusing at first, but don't worry, you'll get used to it!

For loop variations

On a last note specifically about the for loop, I want to show you that it's even more customizable than you may expect: You can leave out parts of it (all parts, in fact, but that would result in an endless loop), and you are in complete control of the step-part, meaning that you can increase or decrease it by 1 or any other positive number on each iteration. Here's an example:

let counter = 2;
	
for(; counter <= 10;)
{
	document.write(counter);
	counter = counter + 2;
}

I know it might look strange, but let me walk you through it:

  • No variable is declared in the for loop - we do that before the loop. However, the for loop requires 3 parts, so we simply place a semicolon, to indicate that we don't need to declare a loop variable
  • The condition is the same as before
  • But we also leave out the step part
  • Instead, we work directly with the counter variable inside of the loop, increasing it by 2 instead of 1, on each iteration

The result is a list of even numbers from 2 to 10. Now, this is mainly to show you the flexibility of the for loop - you will likely not use it a lot, compared to the more common version I showed you first.

Controlling the loop: break and continue

Sometimes you'll find yourself in a situation where you need to take further control of the loop while you're already inside of it. JavaScript comes with two keywords which are (almost) only used exclusively for loops: break and continue. Let's see what they can do for you.

continue

The continue keyword can be used inside of a loop to instruct the interpreter to skip the rest of the code inside the loop and go to the next iteration. It's usually as a result of some kind of internal check within the loop. Here's a simple example showing you how it works:

for(let counter = 1; counter <= 10; counter++)
{
	if(counter % 2 != 0)
		continue;
	document.write(counter);	
}

We basically count from 1 to 10, but inside the loop, we check if the counter is an equal number (using the % (remainder) operator - more on that later), and if it's not, we jump to the next iteration with the continue keyword. This allows us to only print equal numbers, and while this example alone is not terribly useful, you will quickly find yourself in a situation where the ability to jump back to the start of the loop and on to the next iteration. But what if you want to completely exit the loop?

break

To completely exit a loop before time, we have the break keyword. It will immediately exit the loop and then move on to the next lines after the loop. Here's an example:

for(let counter = 1; counter <= 10; counter++)
{
	document.write(counter);
	if(counter >= 5)
		break;
}
document.write("Five is enough...");

Once again, we count from 1 to 10, but inside the loop, we suddenly decide that we only want to count to 5, so as soon as we reach that number, we exit the loop and move on.

And of course, both continue and break can be used in a while loop too, even in combination - here's an example just to prove the point:

let counter = 0;
while(counter <= 20)
{
	counter = counter + 1;
	
	if(counter % 2 != 0)
		continue;
	document.write(counter);
	if(counter >= 10)
		break;
	
}
document.write("Ten is enough...");

Quick summary: We count from 0 to 20, but if the counter is not equal, we skip to the next iteration, and as soon as the counter reaches 10, we exit the loop. All of this just to show you a combination of the continue and break keywords within a while loop.

Summary

Loops allow you to repeat the same code multiple times, but with different results, as we saw in the examples of this article. Whether you use the while or the for loop really depends on the situation you're in, but in many cases, both are usable and whether you use one or the other sometimes come down to personal taste.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!