JavaScript Tutorial: How to Use Loops

JavaScript Loops Tutorial: Learn how to use Loops to iterate over data

Share This Post

The best part of programming is that you can automate stuff. In fact, you don’t want to embark on repetitive tasks. You want the computer to do it for you. In JavaScript, loops are the king of repetition: they allow the computer to repeat the same thing many times. In this JavaScript tutorial, we will see how to use them and why.

This JavaScript tutorial assumes you already grasp the basics of JavaScript. If you don’t, you may want to start from this getting started article.

What are Loops in JavaScript?

To better understand loops in JavaScript, we can compare them with the if-else statement from our previous tutorial. With the if-else statement, in fact, we execute some arbitrary code if a specific condition is true. However, with the if-else statement, we check the condition and execute the code if it is true. Instead, with a loop, we repeatedly execute the code as long as the condition remains true.

Think of it this way: in a loop, we check a condition, execute the code if that condition is true, and then check the condition again. We repeat this process, potentially forever, as long as the condition remains true.

Why would you want to use something like that? Loops have many use-cases, and they are crucial to any programming language. You can use them to count things, find values, search and more. In this JavaScript loops tutorial article we will just start from the basics, but the potentiality of these features go way beyond that.

Specifically, loops can start to be extremely useful when you work with complex data structures, such as arrays or objects.

How to Use Loops in JavaScript

All loops implement the same concept, but in slightly different ways. In this post, we will see how to use all the three flavors of loop in JavaScript, specifically:

  • While loop
  • For loop
  • do…while loop

Furthermore, we will also see how to tweak any of those loop a little with the break and continue statements.

While Loop in JavaScript

The while loop is just what it sounds like. It tells JavaScript “while this condition is true, execute this code”. The syntax is the one below.

while (CONDITION) {
  SOME CODE
}

The easiest way to test it is to try to increment a variable until it reaches a given threshoold. In the following example, we increment the variable i up until it reaches the value of 10.

let i = 0;
while (i < 10) {
  console.log("i=" + i);
  i += 1;
}
console.log("Finished!");

Note the instruction i += 1. It means “assign to i the value of itself plus i“, it is a shortcut for i = i + 1. We can use the same construct to add any value (e.g. i += 10). However, if we want to increment just by one we could also simply use i++. If we run this code, we get the following output.

i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
Finished!

An important note: with a while loop, we check the condition and if it is true we execute the code. As such, if the condition is not true the first time, the loop will never be execute. In technical jargon, we say that we do not enter the loop, because we never execute the code inside it.

For Loop in JavaScript

The while loop is very flexible, we can use pretty much any condition and any code. Instead, the for loop is designed specifically for repeating a task N times. Indeed, we call this “for” because we can say do this task for N times.

Unlike other loops, its syntax demands three parts:

  • Initialization – a simple instruction to execute before running the loop.
  • Condition – the condition to check before each iteration of the loop.
  • Increment – an additional instruction to execute once the code in the code block has been executed. Typically, this means increasing a counter.

We need to use semicolons to separate these three parts:

for (INITIALIZATION; CONDITION; INCREMENT) {
  SOME CODE
}

This may sound a little abstract, but an example will definitely make things clearer. In the following code snippet, we implement the same functionality we used with the while loop, but with a for loop.

for (let i = 0; i < 10; i++) {
  console.log("i=" + i);
}
console.log("Finished!");

As you can see, the initialization of the counter variable (i) happens inside the for (let i = 0). The condition (i < 10) is the same as before, and the increment instruction (i++) is also inside the loop.

The main advantace of the for syntax over a while loop is that it is more compact. Furthermore, you don’t need to take care of the increment in your code block, making it more readable.

Do…While Loop

This type of loop is rarely used, in fact I almost never saw it in “real” code. However, it is something that you may want to know, at least academically. Plus, it’s very simple.

In short, a do…while loop works exactly like a while loop, except one thing: it execute the code block first, and check the condition afterwards. As a result, you are always granted that your code will execute at least once. Check the syntax to believe this for yourself.

do {
  SOME CODE
} while (CONDITION);

We can run the same implementation as we did in the previous two loops, but it will be slightly different. Take a look at it.

let i = 0;
do {
  console.log("i=" + i);
  i += 1;
} while (i < 11);
console.log("Finished!");

This will yield the same output as in the previous two examples. However, you can see that here the condition is i < 11, and not i < 10. This is because we know that when i actually reaches the value of 10, it has not been printed. More specifically, we print i=9 and then i becomes 10. If we use i < 10, that condition would be false, and we would exit the loop with the last value printed being 9.

Tweaking the Loops

A Warning, Infinite Loops

An infinite loop is something you don’t want, unless you have a way to exit out of it. In fact, an infinite loops is a loop that never ends, the code continues to be repeated over and over, forever.

As you can imagine, forever does not have an end, and the computer doesn’t really like that. Theoretically, it may just continue forever until the PC breaks, consuming all its computing resources for nothing. Fortunately, modern browsers have a timeout and if your application hang in an infinite loop they will just kill it and make it crash.

So, your loops need to always have a way to finish. This may be related to the condition of the loop, or to the tuning commands we are about to see.

Break

The break instruction, well, breaks the loop. This means it can allow you to decide to exit the loop inside the code of the loop, regardless if the condition is true or not.

A common approach is to pair it with an if statement: we check somthing every time we run the loop, and if it is true we exit the loop. As we will see in later tutorials, this is extremely useful when we are seaching something into a list of items: we can easily exit the loop as soon as we find it.

In the following example, we run an infinite loop – one that can never end by itself. However, we terminate it using a break statement once the value of i reaches 0. Obviously, in that very specific example we could have used the while condition normally without any problem. We are just using it to explain you the syntax.

let i = 100;
while (true) {
  if (i === 0) {
    break;
  }
  console.log("i=" + i);
  i -= 1;
}

Continue

The continue instruction is the opposite of break. It tells JavaScript to skip the remaining code in the code block, and go directly to the next iteration. This is useful when you are processing data that can be of different types and you want to process only a subset of them. With the continue, you can just skip the data you don’t want to process.

let i = 10;
while (i > 0) {
  i -= 1;
  if (i % 2 === 0) {
    continue;
  }
  console.log("i=" + i);
}
console.log("Finished");

In this example, as you can see below, we skip all the even numbers (i % 2 === 0 is true for even numbers).

i=9
i=7
i=5
i=3
i=1
Finished!

Just like with break, you can use continue in any loop, not just in a while.

Loops for Full Stack Developers

As part of our Full Stack Development course, we are doing some exercises to test the new concepts we learn. This JavaScript tutorial makes no exception, so we are going to practice with loops.

To do that, we continue our pretend bakery store website project by adding a loop to it. If you are new to this, you can take a look at the project on github.com.

Assignment

For this JavaScript tutorial on loops, you should implement a loop that performs the Fibonacci sequence up to the first number in the sequence which is smaller than 1000.

In case you need a refresher, each number in the Fibonacci sequence is the sum of the previous two in the sequence, starting from 0 and 1. This means that the first number is 0, the second is 1, the third is also 1 (0 + 1), the fourth is 2 (1 + 1), the fifth is 3 (2 + 1), and so on. We can easily visualize it as follow.

0 1 1 2 3 5 8 13 21 34 55 ...

It can go on forever, but for further reference you can check out the Fibonacci number on Wikipedia.

We should not limit ourselves to print the number. We should print out how it was calculated, the two numbers that compose it. Our code should stop printing when the sum reaches the highest number below 1000.

To achieve this, we should use two global variables (a and b) and one variable inside the loop, that we can call total. The output that we want is exactly the following.

0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13
8 + 13 = 21
13 + 21 = 34
21 + 34 = 55
34 + 55 = 89
55 + 89 = 144
89 + 144 = 233
144 + 233 = 377
233 + 377 = 610
377 + 610 = 987

Try figuring this out by yourself before checking out the solution below.

Solution

You can check out the solution on GitHub.com at alessandromaggio/full-stack-course, and specifically look at this commit that contains the solution.

So, to start we need to use two variables to hold our two “previous” number that we will sum together to calculate our next one. We can initialize them to the first two numbers in the sequence.

let a = 0;
let b = 1;

Then, we need to loop some instructions. As this is not just a linear increment of N times, we rule out the for loop. Furthermore, our requirements ask us to not print if the total surpasses 1000, and this means we need to check before printing, so we rule out the do…while. We should use the while loop.

In the loop, we need to check the total against 1000, but since we don’t have a variable for that we can compute it on the fly (a + b).

while (a + b < 1000) { }

Now, what do we do inside the loop? For sure we need to store the total somewhere, in the variable named total. Then, we need to print it out with the format required, and then do the increments.

Incrementing here is not just like increasing a number. We need to ensure that a assumes the value that b had (because b was bigger), and b assumes the value of total. So here’s the full solution.

let a = 0;
let b = 1;
while(a + b < 1000) {
  let total = a + b;
  console.log(a + ' + ' + b + ' = ' + total);
  a = b;
  b = total;
}

Wrap Up

In this JavaScript tutorial, we saw how to implement loops in Javascript. At some point, the use of loops may still seem limited to you, and that’s because we have only worked with simple variables. However, loops are at the foundation of working with complex structures like arrays or objects, so you should start to be familiar with loops before we go onto something more complex.

Try mixing things up, and doing different loops to achieve different results. Be familiar with the syntax, particularly with while and for (sorry do…while).

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio

2021-01-21T16:30:04+00:00

Unspecified

Full Stack Development Course

Unspecified