Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Loops: for, while, do...while and Iteration

Learn how JavaScript loops work using for, while and do...while statements, including loop control, nested loops, iteration patterns and practical web development examples.

🎯

Learning Objectives

["Understand why loops are used in JavaScript programming.","Explain the difference between iteration and conditional execution.","Use for loops to repeat a block of code a specific number of times.","Understand initialization, condition and update expressions in a for loop.","Use while loops when the number of iterations is not known in advance.","Use do...while loops when code must execute at least once.","Use break to terminate a loop early.","Use continue to skip the current iteration and continue looping.","Understand nested loops and when they are useful.","Avoid infinite loops by writing safe loop conditions.","Use loops to work with arrays and collections.","Choose the appropriate loop structure for a practical programming problem."]

📖

Lesson Content

Introduction

Web applications often need to perform the same operation many times. For example, a learning management system may need to display every course, a dashboard may need to process a list of students, and an online store may need to display every product returned from a database.

Writing the same instruction repeatedly would make a program unnecessarily long and difficult to maintain.

JavaScript solves this problem with loops.

A loop repeatedly executes a block of code while a specified condition remains true or while there are still items to process.

In this lesson, you will learn:

  • for loops
  • while loops
  • do...while loops
  • break
  • continue
  • Nested loops
  • Looping through arrays
  • Common loop mistakes

1. What Is Iteration?

Iteration means repeating a process.

For example, imagine you need to print the numbers from 1 to 5:

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

This works, but it becomes inefficient when you need to process hundreds or thousands of values.

A loop provides a much better solution:

for (let number = 1; number <= 5; number++) {
    console.log(number);
}

The loop automatically repeats the operation.


2. The for Loop

The for loop is one of the most commonly used JavaScript loops.

Its basic structure is:

for (initialization; condition; update) {
    // Code to repeat
}

The three parts have different responsibilities.

  • Initialization creates or sets the loop counter.
  • Condition determines whether the loop should continue.
  • Update changes the counter after each iteration.

Example:

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

The output is:

1
2
3
4
5

3. Understanding the for Loop Step by Step

Consider:

for (let i = 1; i <= 3; i++) {
    console.log(i);
}

JavaScript processes it approximately like this:

  1. Create i and set it to 1.
  2. Check whether i <= 3.
  3. Run the code inside the loop.
  4. Increase i by 1.
  5. Check the condition again.
  6. Repeat until the condition becomes false.

When i becomes 4, the condition i <= 3 is false, so the loop stops.


4. Counting Down with a for Loop

A loop does not have to count upward.

for (let i = 5; i >= 1; i--) {
    console.log(i);
}

The output is:

5
4
3
2
1

The update expression uses i-- instead of i++.


5. Using Different Step Sizes

You can increase a loop counter by values other than one.

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

This produces:

0
2
4
6
8
10

The expression i += 2 increases the value by two after each iteration.


6. Looping Through an Array

Loops become particularly useful when working with arrays.

const students = [
    "Ade",
    "John",
    "Mary",
    "David"
];

for (let i = 0; i < students.length; i++) {
    console.log(students[i]);
}

The length property tells JavaScript how many items are in the array.

The expression:

students[i]

retrieves the item at the current index.


7. Array Indexes

JavaScript arrays use zero-based indexing.

That means the first item has index 0.

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

console.log(courses[0]);
console.log(courses[1]);
console.log(courses[2]);

The output is:

Web Development
Data Analysis
Cyber Security

When using a traditional for loop, start the index at 0 and continue while it is less than the array’s length.


8. The while Loop

The while loop executes a block of code as long as its condition remains true.

Basic structure:

while (condition) {
    // Code to repeat
}

Example:

let count = 1;

while (count <= 5) {
    console.log(count);
    count++;
}

The loop continues while count <= 5 is true.


9. When Should You Use while?

A while loop is useful when you do not necessarily know beforehand how many times the loop needs to execute.

For example:

let attempts = 0;
const maximumAttempts = 3;

while (attempts < maximumAttempts) {
    console.log("Checking...");
    attempts++;
}

The number of repetitions is controlled by a condition.

In real applications, a loop might continue while there are records to process, while a value remains valid, or while an application state remains active.


10. The do…while Loop

The do...while loop is similar to a while loop, but there is an important difference.

A do...while loop executes its code at least once before checking the condition.

Structure:

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

Example:

let number = 1;

do {
    console.log(number);
    number++;
} while (number <= 5);

11. while versus do…while

Consider this while loop:

let number = 10;

while (number < 5) {
    console.log(number);
}

Nothing is displayed because the condition is false before the first iteration.

Now consider:

let number = 10;

do {
    console.log(number);
} while (number < 5);

The value 10 is displayed once because the do block runs before the condition is checked.

This is the key difference:

  • while checks first, then executes.
  • do...while executes first, then checks.

12. The break Statement

The break statement immediately stops a loop.

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;
    }

    console.log(i);
}

The output is:

1
2
3
4

When i becomes 5, the break statement terminates the loop.

break is useful when the required item has been found or when continuing the loop is no longer necessary.


13. The continue Statement

The continue statement skips the current iteration and moves to the next iteration.

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }

    console.log(i);
}

The output is:

1
2
4
5

Only the iteration where i equals 3 is skipped.


14. break versus continue

StatementPurpose
breakStops the entire loop.
continueSkips the current iteration.

Understanding this difference is important when controlling loop behavior.


15. Nested Loops

A loop can contain another loop. This is called a nested loop.

Example:

for (let row = 1; row <= 3; row++) {
    for (let column = 1; column <= 3; column++) {
        console.log(`Row ${row}, Column ${column}`);
    }
}

The inner loop runs completely for every iteration of the outer loop.

Nested loops are useful for working with grids, tables, matrices and combinations of data.

However, deeply nested loops can make code difficult to understand and may increase processing time, so use them carefully.


16. Looping Through Course Data

Imagine that a website has a list of courses:

const courses = [
    "Web Development",
    "WordPress Development",
    "Data Analysis",
    "Cyber Security",
    "Graphics Design"
];

for (let i = 0; i < courses.length; i++) {
    console.log(`Course ${i + 1}: ${courses[i]}`);
}

This could be used as part of a larger system that dynamically generates course cards on a webpage.


17. Looping Through Student Records

const students = [
    {
        name: "Ade",
        score: 82
    },
    {
        name: "Mary",
        score: 74
    },
    {
        name: "John",
        score: 45
    }
];

for (let i = 0; i < students.length; i++) {
    const student = students[i];

    console.log(
        `${student.name}: ${student.score}`
    );
}

This demonstrates how loops can process objects stored inside arrays.


18. for…of Loop

JavaScript also provides the for...of loop, which is convenient for iterating over values in an iterable such as an array.

const courses = [
    "Web Development",
    "Data Analysis",
    "Cyber Security"
];

for (const course of courses) {
    console.log(course);
}

This is often easier to read than manually working with array indexes when you only need each value.


19. for…in Loop

The for...in loop is commonly used to iterate over enumerable property names of an object.

const student = {
    name: "Ade",
    course: "Web Development",
    score: 85
};

for (const property in student) {
    console.log(property, student[property]);
}

The loop provides each property name, which can then be used to access its value.

For arrays, prefer array-oriented iteration methods or for...of when you need values. for...in is generally intended for object properties.


20. Avoiding Infinite Loops

An infinite loop occurs when a loop’s condition never becomes false.

For example:

let number = 1;

while (number <= 5) {
    console.log(number);
}

The problem is that number never changes, so the condition remains true forever.

The corrected version is:

let number = 1;

while (number <= 5) {
    console.log(number);
    number++;
}

Always make sure that a loop has a clear path toward becoming false.


21. Common Loop Mistakes

Mistake 1: Incorrect Starting Value

for (let i = 1; i < students.length; i++) {
    console.log(students[i]);
}

This skips the first array item because array indexes normally begin at 0.

Mistake 2: Incorrect Boundary

For an array, this is usually correct:

i < students.length

rather than:

i <= students.length

The second condition can cause an extra iteration where the index is outside the valid range.

Mistake 3: Forgetting the Update

let count = 1;

while (count <= 5) {
    console.log(count);
}

Without updating count, this becomes an infinite loop.

Mistake 4: Modifying Data Unexpectedly

Be careful when changing an array or collection while iterating through it. Such changes can cause items to be skipped or processed unexpectedly.


22. Loop Control with Conditions

Loops can be combined with conditional statements to create more useful logic.

for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        console.log(`${i} is even`);
    } else {
        console.log(`${i} is odd`);
    }
}

This loop uses the remainder operator to determine whether each number is even or odd.


23. Practical Web Development Example

Imagine a course dashboard containing lessons.

const lessons = [
    "HTML Fundamentals",
    "CSS Fundamentals",
    "Responsive Design",
    "JavaScript Basics",
    "JavaScript Loops"
];

for (let i = 0; i < lessons.length; i++) {
    const lessonNumber = i + 1;

    console.log(
        `Lesson ${lessonNumber}: ${lessons[i]}`
    );
}

This pattern can later be combined with the DOM to generate lesson cards dynamically on a webpage.


24. Practical Example: Search for a Student

const students = [
    "Ade",
    "Mary",
    "John",
    "David"
];

const target = "John";

for (let i = 0; i < students.length; i++) {
    if (students[i] === target) {
        console.log("Student found.");
        break;
    }
}

Once the target student is found, there is no reason to continue checking the remaining items, so break ends the loop.


25. Practical Example: Skip Inactive Students

const students = [
    { name: "Ade", active: true },
    { name: "Mary", active: false },
    { name: "John", active: true }
];

for (const student of students) {
    if (!student.active) {
        continue;
    }

    console.log(`Active student: ${student.name}`);
}

The inactive student is skipped while the loop continues processing the remaining records.


26. Choosing the Right Loop

LoopTypical Use
forWhen you have a clear counter or iteration structure.
whileWhen repetition depends primarily on a condition.
do...whileWhen the code must execute at least once.
for...ofWhen you want values from an iterable such as an array.
for...inWhen iterating over enumerable object property names.

27. Performance Considerations

Loops are powerful, but the amount of work performed inside a loop matters.

For example, avoid performing expensive operations repeatedly when the result can be calculated once outside the loop.

const students = [
    "Ade",
    "Mary",
    "John"
];

const totalStudents = students.length;

for (let i = 0; i < totalStudents; i++) {
    console.log(students[i]);
}

Modern JavaScript engines can optimize many common loop patterns, but writing clear and efficient loops remains an important programming skill.


28. Mini Project: Course List Generator

Create a JavaScript program that processes a list of Dwallnet courses.

Your program should:

  1. Create an array containing at least five courses.
  2. Use a loop to display every course.
  3. Display the course number beside each course.
  4. Skip a course when a specified condition is met.
  5. Stop searching when a target course is found.

Example:

const courses = [
    "Web Development",
    "WordPress Development",
    "Data Analysis",
    "Cyber Security",
    "Graphics Design"
];

for (let i = 0; i < courses.length; i++) {
    console.log(`${i + 1}. ${courses[i]}`);

    if (courses[i] === "Cyber Security") {
        console.log("Target course found.");
        break;
    }
}

29. Loops and Dynamic Websites

Loops become especially important when JavaScript interacts with the Document Object Model (DOM).

For example, a JavaScript application can loop through a list of products and create a card for each product.

A simplified example is:

const products = [
    "Laptop",
    "Keyboard",
    "Mouse"
];

for (const product of products) {
    console.log(`Create card for: ${product}`);
}

In a later lesson, you will learn how to use the DOM to turn this kind of data into actual HTML elements displayed in the browser.


30. Best Practices for JavaScript Loops

  • Use a loop that clearly communicates your intention.
  • Make loop conditions easy to understand.
  • Always ensure that a loop can eventually terminate.
  • Avoid unnecessary deep nesting.
  • Use break when searching and the result has already been found.
  • Use continue only when skipping an iteration improves clarity.
  • Use for...of when you need array values and do not need indexes.
  • Use for...in primarily for object properties.
  • Keep complex operations outside loops when they do not need to be repeated.
  • Use meaningful variable names instead of unclear counters when appropriate.

Lesson Summary

Loops allow JavaScript programs to repeat operations efficiently. The for loop is useful when you have a clear iteration structure, while while is useful when repetition depends on a condition. The do...while loop guarantees at least one execution.

The break statement terminates a loop, while continue skips the current iteration. JavaScript also provides for...of for iterating over values and for...in for object property names.

Loops are fundamental to web development because they allow applications to process arrays, display lists, handle records and perform repetitive operations without duplicating code.


Practice Exercise

  1. Write a for loop that prints numbers from 1 to 20.
  2. Write a loop that prints only even numbers from 2 to 20.
  3. Create a while loop that counts from 10 down to 1.
  4. Create a do...while loop that displays a message at least once.
  5. Create an array containing five student names and loop through it using for...of.
  6. Create an object representing a student and use for...in to display its properties.
  7. Use break to stop a loop when a specific number is reached.
  8. Use continue to skip all odd numbers.
  9. Create a nested loop that displays a 5 × 5 grid of row and column numbers.
  10. Build a simple course list generator that displays every course with its number.
💻

Code Example

const courses = [
    "Web Development",
    "WordPress Development",
    "Data Analysis",
    "Cyber Security",
    "Graphics Design"
];

// Traditional for loop
for (let i = 0; i < courses.length; i++) {
    console.log(`${i + 1}. ${courses[i]}`);
}

// for...of loop
for (const course of courses) {
    console.log(`Course: ${course}`);
}

// while loop
let count = 1;

while (count <= 3) {
    console.log(`Attempt ${count}`);
    count++;
}

// do...while loop
let number = 1;

do {
    console.log(`Number: ${number}`);
    number++;
} while (number <= 3);

// break
for (let i = 1; i <= 10; i++) {
    if (i === 6) {
        break;
    }

    console.log(`Before break: ${i}`);
}

// continue
for (let i = 1; i <= 10; i++) {
    if (i % 2 !== 0) {
        continue;
    }

    console.log(`Even number: ${i}`);
}

// Nested loop
for (let row = 1; row <= 3; row++) {
    for (let column = 1; column <= 3; column++) {
        console.log(`Row ${row}, Column ${column}`);
    }
}
⭐

Key Takeaways

["Loops repeat code efficiently without unnecessary duplication.","The for loop is useful when the iteration structure is clearly defined.","A for loop commonly contains initialization, condition and update expressions.","The while loop repeats code while a condition remains true.","The do...while loop executes its block at least once before checking the condition.","break immediately terminates a loop.","continue skips the current iteration and proceeds to the next one.","Nested loops place one loop inside another and are useful for multidimensional data.","for...of is convenient for iterating over values in arrays and other iterables.","for...in is commonly used to iterate over enumerable object property names.","Loop conditions must be designed carefully to avoid infinite loops.","Loops are essential for processing arrays, records, lists and dynamic website content.","Choosing the right loop structure makes JavaScript code clearer and easier to maintain."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress