Skip to main content
JavaScript Basics
CHAPTER 07 Beginner

JavaScript Loops

Updated: May 12, 2026
20 min read

# JavaScript Loops

Imagine you need to write "I will not talk in class" 100 times on a chalkboard. Doing it by hand is exhausting. In programming, whenever we need to repeat an action, we use Loops.

In this chapter, we will learn how to make the computer do the heavy lifting of repetitive tasks effortlessly.

1. Introduction

Loops are used to execute a block of code a number of times. This is incredibly useful when working with lists of data (like a list of users, products, or messages) or when you want an animation to repeat over and over.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Use the for loop to run code a specific number of times.
  • Use the while loop to run code as long as a condition is true.
  • Understand the do...while loop.
  • Use the break statement to exit a loop early.
  • Use the continue statement to skip an iteration.
  • Build a Multiplication Table Generator mini-project.

3. The for Loop

The for loop is the most common loop. You use it when you know exactly how many times you want the code to run.

It has three parts inside its parentheses, separated by semicolons:

  1. 1. Initialization: Run once before the loop starts (e.g., set a counter).
  1. 2. Condition: Checked before every run. If true, the loop runs. If false, it stops.
  1. 3. Increment/Decrement: Run after every loop cycle (e.g., increase the counter).

javascript
1234
// Syntax
for (initialization; condition; increment) {
    // code block to be executed
}

4. The while Loop

The while loop loops through a block of code as long as a specified condition is true. You use this when you don't know exactly how many times the loop should run, but you know when it should stop.

javascript
1234
// Syntax
while (condition) {
    // code block to be executed
}

5. The do...while Loop

This is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

javascript
1234
// Syntax
do {
    // code block to be executed
} while (condition);

---

6. Real-world Examples & Code Snippets

Example 1: Basic for Loop

Let's print numbers 1 to 5.

javascript
1234
// Example JavaScript
for (let i = 1; i <= 5; i++) {
    console.log("Count: " + i);
}

Output Explanation:

  • let i = 1 sets our counter.
  • i <= 5 ensures it runs until i becomes 6.
  • i++ adds 1 to i after every cycle.
Output: Count: 1, Count: 2... up to 5.

Example 2: Counting Backwards

You can decrement (i--) instead of incrementing.

javascript
12345
// Example JavaScript
for (let i = 10; i > 0; i--) {
    console.log("Countdown: " + i);
}
console.log("Blast off!");

Example 3: The while Loop

Let's do the same 1 to 5 count using a while loop.

javascript
1234567
// Example JavaScript
let count = 1;

while (count <= 5) {
    console.log("While Count: " + count);
    count++; // CRITICAL: Without this, the loop runs forever!
}

Example 4: do...while Guarantee

The do...while loop always runs at least once, even if the condition is totally false.

javascript
1234567
// Example JavaScript
let x = 100;

do {
    console.log("This will print exactly once.");
    x++;
} while (x < 5); // 101 is not less than 5, so it stops.

Example 5: The break Statement

The break statement "jumps out" of a loop entirely, terminating it immediately.

javascript
12345678
// Example JavaScript
for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        console.log("Hit number 5, breaking the loop!");
        break; // Loop stops here
    }
    console.log(i);
}

Output Explanation: Prints 1, 2, 3, 4, then breaks.

Example 6: The continue Statement

The continue statement "jumps over" one iteration in the loop, but continues with the next iteration.

javascript
12345678
// Example JavaScript
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        console.log("Skipping 3!");
        continue; // Skips the rest of this cycle
    }
    console.log(i);
}

Output Explanation: Prints 1, 2, "Skipping 3!", 4, 5.

Example 7: Looping to create HTML

This is where loops become very powerful in web development.

html
12345678910111213
<!-- Example HTML -->
<ul id="myList"></ul>

<script>
// Example JavaScript
let listHTML = "";

for (let i = 1; i <= 3; i++) {
    listHTML += "<li>List Item Number " + i + "</li>";
}

document.getElementById("myList").innerHTML = listHTML;
</script>

Output Explanation: Generates three <li> elements dynamically and inserts them into the <ul>.

Example 8: Nested Loops

A loop inside a loop. The inner loop runs completely for *every* single iteration of the outer loop.

javascript
123456
// Example JavaScript
for (let row = 1; row <= 3; row++) {
    for (let col = 1; col <= 2; col++) {
        console.log("Row " + row + " | Col " + col);
    }
}

Output Explanation: Prints Row 1 Col 1, Row 1 Col 2, Row 2 Col 1, Row 2 Col 2, etc.

Example 9: The Infinite Loop Warning

If you forget to increment your counter in a while loop, or create a condition that can never be false, your browser will crash.

javascript
1234567
// Example JavaScript
let num = 1;
/* DANGER: DO NOT RUN THIS
while (num > 0) {
    console.log("This runs forever because num is always greater than 0");
}
*/

Example 10: Loop with User Input

Using a while loop to enforce input rules.

javascript
12345678
// Example JavaScript
/*
let password = "";
while (password !== "secret123") {
    password = prompt("Please enter the correct password:");
}
alert("Access Granted!");
*/

Output Explanation: The prompt will keep reappearing until the user types exactly "secret123".

---

7. Common Mistakes for Beginners

  1. 1. Infinite Loops: Forgetting i++ in a while loop or writing a condition like i > -1 when i is increasing. This freezes the browser tab.
  1. 2. Off-by-One Errors: Writing i < 10 when you actually wanted to include 10 (which requires i <= 10).
  1. 3. Using commas instead of semicolons in a for loop: for (let i=0, i<5, i++) will throw a syntax error. It must be semicolons: for (let i=0; i<5; i++).

8. Best Practices

  • Use for loops when you know the exact number of iterations (e.g., counting from 1 to 10).
  • Use while loops when the number of iterations is unknown and depends on an external condition (e.g., waiting for user input to be correct).
  • Keep loop logic as simple as possible. Heavy calculations inside a loop that runs thousands of times will slow down your website.

9. Mini Project: Multiplication Table Generator

Let's build a tool that generates a math multiplication table dynamically using a for loop.

HTML:

html
1234567891011121314151617181920212223
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; padding: 20px; }
        .table-box { width: 300px; padding: 20px; border: 2px solid #555; background: #f9f9f9; }
        .row { border-bottom: 1px solid #ccc; padding: 5px; }
    </style>
</head>
<body>

    <div class="table-box">
        <h2>Multiplication Table</h2>
        <input type="number" id="baseNum" value="5">
        <button onclick="generateTable()">Generate</button>
        <div id="tableOutput"></div>
    </div>

    <script src="table.js"></script>
</body>
</html>

table.js:

javascript
12345678910111213141516171819
// Example JavaScript
function generateTable() {
    let number = Number(document.getElementById("baseNum").value);
    let outputDiv = document.getElementById("tableOutput");
    
    // Clear previous results
    outputDiv.innerHTML = "";
    
    // Create the table using a loop
    let resultHTML = "";
    
    for (let i = 1; i <= 10; i++) {
        let mathResult = number * i;
        resultHTML += "<div class=&#039;row&#039;>" + number + " x " + i + " = <strong>" + mathResult + "</strong></div>";
    }
    
    // Inject the final string into the DOM
    outputDiv.innerHTML = resultHTML;
}

10. Exercises

  1. 1. Write a for loop that logs all even numbers from 2 to 20 to the console.
  1. 2. Write a while loop that counts down from 5 to 1, then console logs "Happy New Year!".
  1. 3. Create a for loop from 1 to 10. Inside it, use an if statement and the continue keyword to skip the number 7.

11. MCQs (Multiple Choice Questions)

Q1: Which loop is guaranteed to run its code block at least once? A) for loop B) while loop C) do...while loop D) none of the above *Answer: C*

Q2: What is the correct syntax for a for loop? A) for (let i = 0; i < 5; i++) B) for (let i = 0, i < 5, i++) C) for i = 1 to 5 D) loop (i < 5) *Answer: A*

Q3: Which keyword stops a loop entirely? A) stop B) exit C) break D) continue *Answer: C*

12. Interview Questions

Q: Explain the difference between break and continue. *A: break completely terminates the loop and moves the program execution to the code immediately following the loop. continue only terminates the current iteration of the loop, skipping any remaining code in that specific cycle, and jumps back to evaluate the loop's condition for the next iteration.*

Q: What causes an infinite loop and why is it dangerous in JavaScript? *A: An infinite loop occurs when the loop's terminating condition is never met (e.g., a counter is never incremented). In JavaScript, since it is a single-threaded environment, an infinite loop blocks the main thread, freezing the UI and preventing any other code from running until the browser crashes or intervenes.*

13. FAQs

Q: Can I put variables inside the loop's condition that come from outside? *A: Yes! for(let i=0; i < someExternalVariable; i++) is extremely common.*

14. Summary

  • Loops automate repetitive tasks.
  • for loops require initialization, condition, and increment logic.
  • while loops run as long as a condition remains true.
  • do...while loops always execute at least one time.
  • break escapes the loop entirely; continue skips the current iteration.

15. Next Chapter Recommendation

We have written a lot of code, but writing logic straight into the document isn't very organized. What if we want to reuse our multiplication logic in five different places? In the next chapter, JavaScript Functions, we will learn how to package our code into reusable, professional blocks.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·