Creating Loops In JavaScript

In this lesson you'll discover everything you need to know about loops as a beginner, including different kinds of loops with examples.

We will cover:

When it comes to learning programming, the topic of loops are where things start to get really exciting!

What is a loop?

In programming loops are used to repeat a block of code.

For example, if we wanted to print all of the numbers from 1 to 100 we could manually write all of the console.log() statements individually:

console.log(1);
console.log(2);
console.log(3);
...

However this is not very efficient! It would be much better to create a loop to perform this functionality dynamically.

Loops are a core building block in almost any program, and are an essential concept for beginners to learn.

In this lesson we'll explore four different kinds of loop syntax in JavaScript:

  • for
  • while
  • do...while
  • for...of

Although there are other types of loops in JavaScript, these ones will serve you well at the start of your journey. Furthermore, any new looping syntax will be much easier to learn once you have a strong grasp of the styles covered in this lesson.

for

When first learning programming, the syntax of a for loop can seem confusing. The good news, however, is that once you understand it, you'll find it useful throughout your career, and in many programming languages.

We'll start simply by first declaring the loop using the for keyword, together with the same parentheses () and curly braces {} we've seen in if statements:

for () {

}

So far so good! Next let's look at the overall syntax of a for loop:

for (initialization; condition; afterthought) {
	// Code to run
}

Inside the parentheses () there are three elements, separated by semi-colons ;.

  1. The initialization element is executed before starting the loop. It is typically used to initialise a counter variable.
  2. The condition is an expression that is evaluated on each iteration to check if the loop should stop. If it is true, the loop keeps going. If it is false, the loop ends.
  3. The afterthought is run at the end of each iteration, and before the next evaluation of the condition. This is typically used to update or increment a counter variable (that was initialised at the start).

Example

This is a lot to take in, so let's explore each part of the for loop's syntax and behaviour with an example. We'll log a message to the console for each iteration of the loop, including the iteration number.

We'll begin by declaring the for loop and the initialiser variable:

for (let i = 1) {

}

You may be wondering why we're using the letter i - this is a common convention in programming and stands for 'iterator' or 'index'. It's essentially a count, and here we're starting at 1.

We want to log a message to the console five times, so the loop requires five iterations. We'll therefore set the condition as i <= 5 so that the loop continues while i (our count) is less than or equal to 5:

for (let i = 1; i <= 5) {

}

In order for the loop to continue we need to declare the afterthought and increment i. We can use the increment ++ operator:

for (let i = 1; i <= 5; i++) {

}

Notice that this time the increment ++ operator follows the i variable (i++), instead of preceding it (++i). The difference is that i++ returns the value of i before incrementing, while ++i returns the value of i after incrementing. There is no practical difference for us in JavaScript, however i++ is a convention that originated in the C programming language (on which JavaScript is based).

Now that we have declared the initializer variable, the condition, and the afterthought, we can move on to writing the console.log() statement inside the curly braces {}:

for (let i = 1; i <= 5; i++) {
	console.log('Iteration count: ' + i);
}

Above we're using string concatenation to output the value of i for each iteration.

If you now run the code you should see the following output in the console:

Iteration count: 1
Iteration count: 2
Iteration count: 3
Iteration count: 4
Iteration count: 5

The message is logged five times, with the value of i incrementing each time.

Iteration breakdown

So what exactly is going on here? Let's go over the for loop syntax again, breaking down how the iteration works in detail.

In the first iteration:

  • i is set to the value 1.
  • The loop checks if i is less than or equal to 5 (with the condition i <= 5).
  • i is 1, so the condition is true.
  • The code block inside the curly braces {} is executed.
  • After the console.log() statement is run, i is incremented by 1 to become 2.

From this point the initialization is ignored because it only runs at the start of the loop.

This leads to the second iteration:

  • The condition is evaluated again.
  • This time i is 2, so the condition is still true (as 2 is less than or equal to 5).
  • The code within the curly braces {} is executed again, this time with i being 2.
  • i is then incremented again to become 3.

This process continues for when i is equal to 3, 4, and 5. On the sixth iteration:

  • i is incremented to 6.
  • The condition i <= 5 now evaluates to false.
  • The loop ends.

Using a for loop we only need to write the conole.log() statement once, and we are able to execute it five times. As you can hopefully see, loops are incredibly powerful!

To print the console statement 100 times, all we would need to do is change the condition to i <= 100, for example:

for (let i = 1; i <= 100; i++) {
	console.log('Iteration count: ' + i);
}

This is much better than writing the statement manually 100 times!

while

The next looping construct we'll explore is the while loop. The syntax for a while loop is actually somewhat simpler than the for loop:

while (condition) {
	// Code to run
}

It looks almost exactly like an if statement, and behaves in a similar way.

We start with the while keyword and then specify a condition to evaluate in parentheses ().

The code block inside the curly braces {} will be executed while the condition evaluates to true. The loop will continue to iterate until the condition evaluates to false, at which point the loop is terminated.

Example

Once again let's look at an example. Building on our knowledge of the for loop, we'll reproduce the same functionality from the previous example with the while loop.

We'll start by initialising a count variable to 1:

let i = 1;

Next we can declare the while loop:

let i = 1;

while () {

}

The condition to evaluate will be the same as before, checking if i is less than or equal to 5:

let i = 1;

while (i <= 5) {

}

Inside the code block we will specify the statement that we want to execute for each iteration. We will use the same console.log() statement from the previous example:

let i = 1;

while (i <= 5) {
	console.log('Iteration count: ' + i);
}

We also need to increment the count every time the loop iterates, just like before. We can do this at the end of the code block:

let i = 1;

while (i <= 5) {
	console.log('Iteration count: ' + i);
	i++;
}

This pattern of initialising and then incrementing a count is a commonly used technique in programming. It's worth noting that this is not an essential part of the while loop's syntax, it's just one example. In other cases you may need to evaluate some other type of condition.

Now if we run the code we should see the same result as before in the terminal:

Iteration count: 1
Iteration count: 2
Iteration count: 3
Iteration count: 4
Iteration count: 5

Iteration breakdown

The execution of the while loop is very similar to the for loop. In the first iteration:

  • i is initialised to 1.
  • The condition i <= 5 is evaluated as true.
  • The code block is executed.
  • i is incremented by 1.

This process continues until the value of i is incremented to 6, at which point the condition i <= 5 evaluates to false, and the loop ends.

The structure of the while loop is easier to understand once you've understood how the for loop works.

Again, this can be a lot to take in as a beginner, so take your time. This knowledge is hugely valuable and you will layer on it as you move forward.

do...while

The do...while loop is a variation on the while loop, with the following syntax:

do {
	// Code to run
} while (condition);

The do...while loop functions almost exactly the same as a regular while loop, except that the code block in the curly braces {} is always executed at least once.

This is because the condition is evaluated after the code within the loop has run for the first time.

Example

To demonstrate the do...while loop we'll again begin by initialising a count:

let i = 1;

Next we'll declare the do part of the loop and add the console.log() statement:

let i = 1;

do {
	console.log('Iteration count: ' + i);
}

Again we need to increment the value of i like so:

let i = 1;

do {
	console.log('Iteration count: ' + i);
	i++;
}

Finally, after the closing curly brace we specify the condition we wish to evaluate:

let i = 1;

do {
	console.log('Iteration count: ' + i);
	i++;
} while (i <= 5);

If we now run the code we should see exactly the same output in the console as before:

Iteration count: 1
Iteration count: 2
Iteration count: 3
Iteration count: 4
Iteration count: 5

So what's new? Well, if we instead initialise the count variable with the value 6 the result will be very different.

let i = 6;

do {
	console.log('Iteration count: ' + i);
	i++;
} while (i <= 5);

When we run the above code we see the following output in the terminal:

Iteration count: 6

Even though 6 is greater than 5, the statement in the curly braces is still executed a single time. This is because the condition i <= 5 is only evaluated after the do code block has run at least once.

The loop is then terminated after executing the statement once, because the condition evaluates to false.

for...of

The for...of loop is most often used to iterate over a collection of data, such as an array. The basic syntax is as follows:

for (variable of iterable) {
	// Code to run
}

A more practical way to illustrate this would be as below, where the collection is an array of items:

for (const item of itemsArray) {
	// Code to run
}

The loop definition starts with the for keyword followed by parentheses (), much like the standard for loop.

However, within the parentheses we now have direct access to each item in the collection, for each iteration. The variable item can be named whatever we like.

Finally, we can write any code that we'd like to execute per iteration within the curly braces {}.

Example

We'll once again aim for the same functionality that we have in the other examples, where we log the number of the iteration to the terminal.

To begin we need to declare an array with the numbers 1 to 5 as items within it:

const numbers = [1, 2, 3, 4, 5];

Next we'll write the for...of loop:

const numbers = [1, 2, 3, 4, 5];

for (const n of numbers) {
	console.log('Iteration count: ' + n);
}

If you run the code you'll see the log statement outputted for each item in the array:

Iteration count: 1
Iteration count: 2
Iteration count: 3
Iteration count: 4
Iteration count: 5

Notice that we did not need to create or increment some kind of count/index variable. Instead, the for...of loop iterates through each item in the array automatically.

In addition, the for...of loop assigns the value of each array item to a variable. In this case we've declared the variable as n.

The console.log() statement is executed much like it was before, this time for each array element i.e. numbers[n].

In the first iteration n is equal to 1. In the second iteration n is equal to 2, and so on until the last item in the array.

Comparison with the for loop

The for...of loop is a great choice when working with arrays because it simplifies the code by abstracting away some manual tasks.

As mentioned, we no longer need to initialise, increment, or keep track of the iteration count. We also don't need to manually access array items.

For example, if we were to tackle the same problem with a for loop, we would need to do something like this:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
	console.log('Iteration count: ' + numbers[i]);
}

As you can see, this code is a bit more verbose. We're initialising a count i at 0 to begin iterating at the first element in the array.

Remember that arrays are zero-indexed in JavaScript, so we begin counting from 0.

The loop will continue until the last item in the array. We use the length property of the array to get the total number of items in the array (in this case 5).

Finally, we increment i as before with i++.

In order to access each array element we use square bracket [] notation (numbers[i]).

Summary

In this lesson you learned about loops in programming and, more specifically, how to write loops in JavaScript!

You also learned how to use the following constructs:

  • for
  • while
  • do...while
  • for...of

This can be a lot to take in, but don't worry about memorising the syntax exactly. It's more important to understand the underlying principles of loops, and to have an awareness that these styles exist.

The different loop constructs are simply tools, and you can revisit them when you have a need to use them.