Codeskill

Learn to code, step by step

Looping the Loop: Understanding For, While, and Do-While Loops

Loops in JavaScript – for, while, and do-while. Loops repeat an action without writing the same code over and over.

The for loop

Use a for loop when you know how many times you want to repeat something.

Syntax

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

Example

for (let i = 0; i < 5; i++) {
    console.log("Loop iteration number " + i);
}

This prints five times, with i going from 0 to 4.

The while loop

A while loop repeats while a condition is true. Useful when you do not know the iteration count in advance.

Syntax

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

Example

let i = 0;
while (i < 5) {
    console.log("Loop iteration number " + i);
    i++;
}

Same output as the for loop above, different structure.

The do-while loop

A do-while loop runs the code block once before checking the condition, then repeats while the condition stays true.

Syntax

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

Example

let i = 0;
do {
    console.log("Loop iteration number " + i);
    i++;
} while (i < 5);

Even if the condition is false from the start, a do-while runs at least once.

Nesting loops

Loops can sit inside other loops – useful for two-dimensional data like matrices.

Nested for loop example

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        console.log(`Row ${i}, Column ${j}`);
    }
}

This walks through rows and columns of a 3×3 grid.

Breaking out of a loop

break exits a loop early.

Example with break

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

The loop stops when i reaches 5.

Skipping an iteration with continue

continue skips the rest of the current iteration and moves to the next one.

Example with continue

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

The number 5 is skipped; the loop carries on.

Practical example: summing an array

Suppose you want the total of every number in an array:

let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

console.log("Sum of the array is: " + sum);

Loops save repetition and keep code readable. Try a few different loop types before moving on to arrays.

PreviousControl Structures: Making Decisions with If-Else and Switch Cases