Get up to 80 % extra points for free! More info:

Lesson 5 - Loops in JavaScript

In the previous exercise, Solved tasks for JavaScript lesson 4, we've practiced our knowledge from previous lessons.

In the previous lesson, Solved tasks for JavaScript lesson 4, we learned how to use conditions in JavaScript. In today's tutorial, we're going to learn all about loops.

Loops

Loops along with conditions make up the basics of each programming language. As you may have guessed, they help us automate tasks that are done many times in a row. If we needed our program to do something 100 times, we would simply place it into a loop. There are a few types of loops which we'll explain when and how to use them. Of course, we have also prepared some practical examples.

For loop

This loop has a predefined number of times it repeats and also contains a so-called control variable (in integer form) whose value is changed while the loop runs. The syntax of the for loop is the following:

for (variable; condition; command)
  • variable is the control variable of the loop to which set the default value (usually 0 because everything begins with zero in programming). For example, let i = 0.
  • condition is the condition that will be verified every step of the loop. Once it's no longer valid, the loop ends. The condition could be something like i < 10.
  • command defines how the control variable will be processed in each step. Meaning whether it should be increased or decreased. To do so we use these special commands ++ and --. These commands can also be used outside of the loop (they increase or decrease any variable by 1).

Let's do a simple exercise, most of us know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a guy knocking on his neighbor's door. He always knocks 3 times and then calls: "Penny!". Our code would look like this without using loops:

document.write("Knock<br />");
document.write("Knock<br />");
document.write("Knock<br />");
document.write("Penny!");

Using loops, we no longer have to copy/paste the code over and over again:

for (let i = 0; i < 3; i++) {
    document.write("Knock<br />");
}
document.write("Penny!");
The for loop in JavaScript
localhost

The loop will run 3 times. At first, zero is stored in the i variable. Then, the loop prints "Knock" and the i variable is increased by one. It then does the same with one and two. Once i is equal to three, the condition i < 3 is not met and therefore the loop ends. We use braces in the same way that we do with conditions. In this case, they don't have to be there because the loop runs only a single command. Now, we can assign the number ten instead of three to the declaration part. The command is printed 10 times and we don't have to write anything else. As you can see, loops are a powerful tool.

Let's try to take advantage of the fact that the variable increments. We'll print the numbers from one to ten into an HTML list.

document.write("<ul>");
for (let i = 1; i <= 10; i++)
    document.write("<li>" + i);
document.write("</ul>");

The result:

The for loop in JavaScript
localhost

We can see that the control variable has a different value in each loop iteration. Notice that we don't begin with zero now, we set 1 to be the default value and 10 to be the final value. However, it is an established programming habit to begin from zero (you'll learn why later).

Now, we'll print a short multiplication table (the multiples of the numbers from 1 to 10). We'll simply loop from 1 to 10 and multiply the variable by the current number. To print the values, we'll use an HTML table like this:

document.write('<table border="1"><tr>');
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 2 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 3 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 4 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 5 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 6 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 7 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 8 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 9 + "</td>");
document.write("</tr><tr>");
for (let i = 1; i <= 10; i++)
    document.write("<td>" + i * 10 + "</td>");
document.write("</tr></table>");
The for loop in JavaScript
localhost

The program works just fine, but we still wrote quite a bit of code. You might have noticed that we're doing the same thing 10 times and the only change is the number used to multiply the variable, which is also incremented. Therefore, we'll simply nest two loops:

document.write('<table border="1">');
for (let j = 1; j <= 10; j++) {
    document.write("<tr>");
    for (let i = 1; i <= 10; i++)
        document.write("<td>" + i * j + "</td>");
    document.write("</tr>");
}
document.write("</table>");

Makes a huge difference, right? Of course, we cannot use the same control variable because they're nested. The j variable also goes from values from 1 to 10. Each loop iteration then runs another loop with the i variable. This one is the one that prints the multiples, in this case, we multiply using the j variable. Each iteration of the nested loop must be inserted into a table row using the <tr> and </tr> tags.

Let's make another program. This time, we'll show how to work with an external variable. The application will be able to calculate any number raised to any exponent:

let a = 2; // Number to be raised
let n = 3; // Exponent

let result = a;
for (let i = 0; i < (n - 1); i++) {
    result = result * a;
}

document.write("Result: " + result);

We all probably know how exponents work. For example, 23 = 2 * 2 * 2. Therefore, an can be calculated by setting a to the result of a multiplied n - 1 times. The result has to be stored in a variable. From the beginning, it will have a value of a which will get multiplied continuously. We can see that our variable result is accessible inside of the loop. However, if we create a variable inside of the loop, the variable will be destroyed and not accessible anymore after the loop ends.

Result:

For loop in JavaScript
localhost

Remember that the number of repeats in the for loop is strictly defined. We should not change the loop's variable because the program might get into an infinite loop. Let's make one more example (don't ever do this):

// this code is wrong
for (let i = 1; i <= 10; i++)
    i = 1;

Ouch! As you can see, the program got stuck. The loop still increments the i variable but it's also always set back to 1. Therefore, it'll never reach a value over 10, and the loop will never end. The page gets stuck while loading and we have to close the tab to kill the script.

While loop

The while loop works a little different. It simply repeats commands until the condition is met. The syntax of this loop is as follows:

while (condition) {
    // commands
}

If you're thinking whether the while loop can be used as a for loop, you're absolutely onto something :) For is something like a special case of the while loop. However, while is used for slightly different things, we often have things like a method which returns some logical value (true/false) in the loop's condition. The original example we made using the for loop can be re-written as follows:

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

However, this is not an ideal usage of the while loop. We'll come back to this loop later on. Next time, Solved tasks for JavaScript lesson 5, we'll look into the array data structure.

In the following exercise, Solved tasks for JavaScript lesson 5, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 11x (3.13 kB)
Application includes source codes in language JavaScript

 

Previous article
Solved tasks for JavaScript lesson 4
All articles in this section
JavaScript Basic Constructs
Skip article
(not recommended)
Solved tasks for JavaScript lesson 5
Article has been written for you by David Capka Hartinger
Avatar
User rating:
4 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities