JavaScript Loops

JavaScriptBeginner
Practice Now

Introduction

In this lab, you will learn how to use loops in JavaScript. Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly. This is useful for tasks like iterating over lists of data or performing an action a specific number of times.

You will explore the three main types of loops in JavaScript:

  • for loop: Repeats a block of code a known number of times.
  • while loop: Repeats a block of code as long as a specified condition is true.
  • do-while loop: Similar to a while loop, but it executes the code block at least once before checking the condition.

You will also learn how to use the break statement to exit a loop early.

All your work will be done in the WebIDE. You will write JavaScript code in the script.js file, which is already linked in index.html. You can see the output of your code by switching to the Web 8080 tab in the lab environment.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 93% completion rate. It has received a 98% positive review rate from learners.

Create for loop with initializer and condition

In this step, you will create your first for loop. The for loop is ideal when you know in advance how many times you want to repeat an action.

The basic syntax of a for loop is:
for (initializer; condition; final-expression) { // code to execute }

  • Initializer: let i = 0 is an example. It runs once at the very beginning to declare and initialize a counter variable.
  • Condition: i < 5 is an example. This expression is checked before each loop iteration. If it's true, the loop continues; if it's false, the loop stops.

Let's create a simple loop that generates a list of items. Open the script.js file from the file explorer on the left and add the following code.

const output = document.getElementById("output");
let htmlContent = "<ul>";

// This for loop has an initializer (let i = 0) and a condition (i < 3)
for (let i = 0; i < 3; i++) {
  htmlContent += `<li>Item ${i}</li>`;
}

htmlContent += "</ul>";
output.innerHTML = htmlContent;

In this code:

  • let i = 0 initializes the loop counter i to 0.
  • i < 3 is the condition that keeps the loop running as long as i is less than 3.
  • i++ is the final-expression that increments the counter after each iteration (we will focus on this in the next step).

After adding the code, save the file. Then, click on the Web 8080 tab to see the output. You should see an unordered list with three items.

Web page showing a list generated by a for loop

Use increment in for loop to count

In this step, you will focus on the third part of the for loop: the final-expression, which is typically used for incrementing the counter.

The final-expression (e.g., i++) runs at the end of each loop iteration. It updates the loop counter, moving it closer to the point where the condition becomes false. i++ is a common shorthand for i = i + 1.

Let's modify the loop to count from 1 to 5. Replace the existing code in script.js with the following:

const output = document.getElementById("output");
let htmlContent = "<h2>Counting from 1 to 5:</h2>";

// The final expression i++ increments the counter after each loop
for (let i = 1; i <= 5; i++) {
  htmlContent += `Count: ${i}<br>`;
}

output.innerHTML = htmlContent;

Notice the changes:

  • The initializer is now let i = 1, so we start counting from 1.
  • The condition is i <= 5, so the loop runs as long as i is less than or equal to 5.
  • The i++ expression ensures the counter increases with each iteration.

Save the file and refresh the Web 8080 tab. You will see the output change to a list of counts from 1 to 5.

Screenshot showing code output counting from 1 to 5

Implement while loop for repetition

In this step, you will learn about the while loop. A while loop continues to execute a block of code as long as a specified condition is true.

The syntax is simpler than a for loop:
while (condition) { // code to execute }

With a while loop, you must handle the initialization of the counter variable before the loop and the incrementing of it inside the loop. Forgetting to increment the counter will result in an infinite loop, which can crash your browser.

Let's rewrite the previous counting example using a while loop. Replace the code in script.js with this:

const output = document.getElementById("output");
let htmlContent = "<h2>Counting with a while loop:</h2>";

let i = 1; // 1. Initializer
while (i <= 5) {
  // 2. Condition
  htmlContent += `Count: ${i}<br>`;
  i++; // 3. Increment
}

output.innerHTML = htmlContent;

This code achieves the same result as the for loop in the previous step, but the structure is different. The initializer, condition, and increment are now separate statements.

Save the file and check the Web 8080 tab. The output should be identical to the previous step, demonstrating a different way to achieve the same repetition.

Add do-while loop for at least one execution

In this step, you will explore the do-while loop. This loop is a variant of the while loop with one key difference: the do-while loop will always execute its code block at least once, before it checks the condition.

The syntax is:
do { // code to execute } while (condition);

This is useful when you need to perform an action first and then decide if you should repeat it. Let's see this in action with an example where the condition is initially false.

Replace the code in script.js with the following:

const output = document.getElementById("output");
let htmlContent = "<h2>Testing a do-while loop:</h2>";

let i = 10; // Start with a value that makes the while condition false

// This loop will run once, even though i is not less than 5
do {
  htmlContent += `The value of i is: ${i}<br>`;
  i++;
} while (i < 5);

output.innerHTML = htmlContent;

In this example, the condition i < 5 is false from the beginning because i is 10. However, because it's a do-while loop, the code inside the do block runs once before the condition is checked.

Save the file and look at the Web 8080 tab. You will see the message "The value of i is: 10", proving that the loop ran exactly one time.

Break out of loop with break statement

In this step, you will learn how to exit a loop prematurely using the break statement. The break statement immediately terminates the current loop and transfers control to the statement following the loop.

This is useful when you are searching for something in a loop and want to stop as soon as you find it, without completing the remaining iterations.

Let's use a for loop that is intended to run 10 times but will stop early when a certain condition is met. Replace the code in script.js with this:

const output = document.getElementById("output");
let htmlContent = "<h2>Using the break statement:</h2>";

for (let i = 1; i <= 10; i++) {
  if (i === 6) {
    htmlContent += "Found 6! Breaking the loop.<br>";
    break; // Exit the loop immediately
  }
  htmlContent += `Current number is ${i}<br>`;
}

htmlContent += "Loop finished.";
output.innerHTML = htmlContent;

In this code, the for loop is set to count from 1 to 10. However, the if statement checks if i is equal to 6. When it is, the break statement is executed, and the loop terminates. The code will not print numbers 7 through 10.

Save the file and view the Web 8080 tab. You will see the count stop at 5, followed by the "Breaking the loop" message.

Summary

Congratulations on completing this lab on JavaScript loops! You have learned how to control the flow of your programs by repeating blocks of code.

In this lab, you covered:

  • The for loop, which is perfect for when you know the number of iterations in advance, using an initializer, a condition, and a final-expression.
  • The while loop, which repeats as long as a condition is true and requires manual management of the counter.
  • The do-while loop, which guarantees at least one execution of the code block before checking the condition.
  • The break statement, which provides a way to exit any loop prematurely based on a condition.

Mastering loops is a critical step in becoming a proficient JavaScript developer. Feel free to experiment further with the code in this lab to solidify your understanding.