⬅ Back

LOOPS

A typical task in programming is to perform the same action many times.

For example, you may need to display clients from a list one by one, or go through salary amounts and run the same code for each one.

Loops are used exactly for this repeated execution of the same part of the code.

Diagram 1. Basic loop idea

Start loop
   ↓
Check condition
   ↓
true  → run loop body → repeat
false → stop loop

Explanation

A loop repeats code while its condition allows it to continue.

1. The while loop

The while construction creates a loop that executes the block of code in the loop body as long as the exit condition evaluates to true.

Syntax

while (condition) {
  statement // code, the loop body
}

The while loop is a precondition loop.

This means the condition is checked before the loop body is executed, so the body may not run even once if the condition is false from the very beginning.

Diagram 2. How while works

while (condition)
│
├─ condition true  → run body
└─ condition false → stop

Explanation

while checks first, then runs the code.

2. while example with a counter

let count = 0;

while (count < 10) {
  console.log(`Count: ${count}`);
  count += 1;
}

In this example, we have a variable count that increases with each iteration.

The while loop will run as long as count is less than 10.

As soon as count becomes equal to or greater than 10, the condition becomes false and the loop ends.

Diagram 3. Counter loop

count = 0

count < 10 ? true  → print and add 1
count < 10 ? true  → print and add 1
...
count = 10
count < 10 ? false → stop

Explanation

The counter must change inside the loop, otherwise the loop may never stop.

3. Task: hotel registration

The variable clientCounter stores the number of occupied rooms at the current moment.

The variable maxClients stores the total number of rooms in the hotel.

Thanks to the while loop, rooms in the hotel will continue to be filled until the current number of clients becomes equal to the maximum allowed number.

let clientCounter = 18;
const maxClients = 25;

while (clientCounter < maxClients) {
  console.log(clientCounter);
  clientCounter += 1;
}

The while loop is often used when the exact number of iterations is not known in advance.

It is important to make sure that the condition of a while loop eventually becomes false, otherwise the loop may run forever.

Diagram 4. Hotel registration loop

clientCounter = 18
maxClients = 25

while clientCounter < maxClients:
print current number
add 1

Stop when clientCounter becomes 25

Explanation

The loop continues while there is still room for more clients.

4. Function example with while

function countClients(clientCounter, maxClients) {
  let counter = clientCounter; // create a local variable

  while (counter < maxClients) {
    console.log(counter);
    counter += 1;
  }
}

countClients(18, 25);

Step-by-step execution

Calling countClients(18, 25):

  1. counter = 18; 18 < 25 is true, so 18 is printed, and counter becomes 19.
  2. counter = 19; 19 < 25 is true, so 19 is printed, and counter becomes 20.
  3. The loop continues until counter = 25, then 25 < 25 is false, and it stops.

Exercises

Exercise 1. Write a while loop that prints numbers from 1 to 5.

let number = 1;

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

Exercise 2. Write a while loop that prints numbers from 5 to 1.

let number = 5;

while (number > 0) {
  console.log(number);
  number--;
}

Exercise 3. Write a while loop that prints only even numbers from 2 to 10.

let number = 2;

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

Exercise 4. Write a while loop that prints only odd numbers from 1 to 9.

let number = 1;

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

5. The do...while loop

JavaScript also has another type of while loop: do...while.

The while and do...while loops work similarly, but they have one key difference.

When using a do...while loop, the code in the loop body runs at least once, even if the condition is false from the very beginning.

Syntax

do {
  statement // code that will be executed
} while (condition);

The block of code inside do runs the first time regardless of whether the condition is true.

Then, after each iteration, the condition is checked.

Diagram 5. How do...while works

do
   ↓
run loop body once
   ↓
check condition
   ↓
true  → repeat
false → stop

Explanation

do...while runs first, then checks the condition.

6. do...while example

let count = 0;

do {
  console.log(`Count: ${count}`);
  count += 1;
} while (count < 5);

In this example, the code inside the do block will run once even if count is greater than or equal to 5.

After that, the condition is checked, and if count is less than 5, the loop continues.

The do...while loop is useful when you need the code in the block to run at least once, regardless of the condition.

Practical example 1: asking for a password

You want to ask at least once:

let password;

do {
  password = prompt("Enter password:");
} while (password !== "1234");

console.log("Access granted");

The question appears at least one time.

Practical example 2: menu

A menu should show at least once:

let choice;

do {
  choice = prompt("Choose: 1 = Start, 2 = Help, 3 = Exit");
  console.log("You chose: " + choice);
} while (choice !== "3");

console.log("Goodbye");

The menu keeps showing until the user chooses 3.

7. The for loop

The for loop also allows repeated execution of code many times.

Unlike while and do...while, the for loop usually has a counter variable.

The counter variable is declared using the let keyword. Using const would cause an error because the counter changes.

Syntax

for (Initialization; Condition; Post-expression) {
  // Loop body
}

Diagram 6. Parts of a for loop

for (let i = 0; i <= 20; i += 5)
     │          │          │
     │          │          └─ post-expression
     │          └─ condition
     └─ initialization

Explanation

A for loop keeps its setup, condition, and counter update in one line.

8. for loop example

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

In this example, the variable i is initialized with the value 0.

The loop runs as long as i is less than or equal to 20.

After each iteration, the value of i increases by 5.

As a result, the numbers 0, 5, 10, 15, and 20 will be printed to the console.

Diagram 7. Counting up by 5

i = 0   → print 0
i = 5   → print 5
i = 10  → print 10
i = 15  → print 15
i = 20  → print 20
i = 25  → condition false, stop

Explanation

The post-expression i += 5 changes the counter after each iteration.

9. Countdown with for

You can also make a countdown by changing the condition and decreasing the counter after each iteration.

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

In this example, i starts at 20.

The loop runs as long as i is greater than or equal to 0.

After each iteration, the value of i decreases by 5.

As a result, the numbers 20, 15, 10, 5, and 0 will be printed.

Diagram 8. Countdown by 5

i = 20  → print 20
i = 15  → print 15
i = 10  → print 10
i = 5   → print 5
i = 0   → print 0
i = -5  → condition false, stop

Explanation

The counter moves down because the post-expression is i -= 5.

Exercises

Exercise 1. Write a for loop that prints numbers from 5 to 1.

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

Exercise 2. Write a for loop that prints 100, 90, 80, 70, 60, and 50.

for (let number = 100; number >= 50; number -= 10) {
  console.log(number);
}

Exercise 3. Write a for loop that prints numbers from 1 to 10.

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

Exercise 4. Write a for loop that prints only even numbers from 2 to 10.

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

Exercise 5. Write a for loop that prints only odd numbers from 1 to 9.

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

Exercise 6. Write a for loop that prints 10, 20, 30, 40, and 50.

for (let number = 10; number <= 50; number += 10) {
  console.log(number);
}

Exercise 7. Write a for loop that prints the multiplication table for 3: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30.

for (let number = 3; number <= 30; number += 3) {
  console.log(number);
}

10. Function example: sum numbers

Let’s write a function that sums all numbers from 0 to a given number and returns the result.

function sumUpTo(number) {
  let sum = 0;

  for (let i = 0; i <= number; i += 1) {
    sum += i;
  }

  return sum;
}

console.log(sumUpTo(5)); // 15
console.log(sumUpTo(10)); // 55
console.log(sumUpTo(0)); // 0

How the function works

  1. It takes one parameter, number, which defines up to which number to sum.
  2. It declares a variable sum and sets it to 0.
  3. It starts a for loop.
  4. It adds the current value of i to sum.
  5. After the loop ends, it returns the total sum.
for (let i = 0; i <= number; i += 1) {
  sum += i;
}

Diagram 9. sumUpTo(5)

sum = 0

i = 0 → sum = 0
i = 1 → sum = 1
i = 2 → sum = 3
i = 3 → sum = 6
i = 4 → sum = 10
i = 5 → sum = 15

return 15

Explanation

The variable sum accumulates the total during the loop.

11. Prefix and postfix increment and decrement in JavaScript

In JavaScript, increment and decrement can be written in two ways: postfix and prefix.

Increment means to increase by 1. Decrement means to decrease by 1.

1. Postfix increment: number++

Postfix increment means: use the current value first, then increase the variable by 1.

let number = 5;

console.log(number++);
console.log(number);
Output:
5
6
Start:
number = 5

console.log(number++)

Step 1:
Use current value.
Print 5.

Step 2:
Increase number by 1.
number = 6

console.log(number)
Print 6.

Simple postfix increment example

let number = 5;

number++;

console.log(number); // 6

When number++ is alone, it simply increases the variable by 1.

2. Prefix increment: ++number

Prefix increment means: increase the variable by 1 first, then use the new value.

let number = 5;

console.log(++number);
console.log(number);
Output:
6
6
Start:
number = 5

console.log(++number)

Step 1:
Increase number by 1.
number = 6

Step 2:
Use the new value.
Print 6.

console.log(number)
Print 6.

Simple prefix increment example

let number = 5;

++number;

console.log(number); // 6

When ++number is alone, it also simply increases the variable by 1.

3. Postfix increment vs prefix increment

Postfix

let x = 5;
let y = x++;

console.log(x); // 6
console.log(y); // 5
Start:
x = 5

y = x++

Step 1:
Use old x.
y = 5

Step 2:
Increase x.
x = 6

Prefix

let x = 5;
let y = ++x;

console.log(x); // 6
console.log(y); // 6
Start:
x = 5

y = ++x

Step 1:
Increase x.
x = 6

Step 2:
Use new x.
y = 6

x++ means use first, then increase. ++x means increase first, then use.

4. Postfix decrement: number--

Postfix decrement means: use the current value first, then decrease the variable by 1.

let number = 5;

console.log(number--);
console.log(number);
Output:
5
4
Start:
number = 5

console.log(number--)

Step 1:
Use current value.
Print 5.

Step 2:
Decrease number by 1.
number = 4

console.log(number)
Print 4.

Simple postfix decrement example

let number = 5;

number--;

console.log(number); // 4

When number-- is alone, it simply decreases the variable by 1.

5. Prefix decrement: --number

Prefix decrement means: decrease the variable by 1 first, then use the new value.

let number = 5;

console.log(--number);
console.log(number);
Output:
4
4
Start:
number = 5

console.log(--number)

Step 1:
Decrease number by 1.
number = 4

Step 2:
Use the new value.
Print 4.

console.log(number)
Print 4.

Simple prefix decrement example

let number = 5;

--number;

console.log(number); // 4

When --number is alone, it also simply decreases the variable by 1.

6. Postfix decrement vs prefix decrement

Postfix

let x = 5;
let y = x--;

console.log(x); // 4
console.log(y); // 5
Start:
x = 5

y = x--

Step 1:
Use old x.
y = 5

Step 2:
Decrease x.
x = 4

Prefix

let x = 5;
let y = --x;

console.log(x); // 4
console.log(y); // 4
Start:
x = 5

y = --x

Step 1:
Decrease x.
x = 4

Step 2:
Use new x.
y = 4

x-- means use first, then decrease. --x means decrease first, then use.

7. All four forms together

let x = 5;

x++;
++x;
x--;
--x;

If they are alone, the result is usually the same.

let x = 5;
x++;
console.log(x); // 6

let y = 5;
++y;
console.log(y); // 6

The difference is important inside expressions such as let result = x++ and let result = ++x.

8. Diagram: postfix vs prefix

Postfix means use first, change after. Prefix means change first, use after.

Postfix increment: x++
Start: x = 5
Use: 5
Then change: x = 6

Prefix increment: ++x
Start: x = 5
Change: x = 6
Then use: 6

Postfix decrement: x--
Start: x = 5
Use: 5
Then change: x = 4

Prefix decrement: --x
Start: x = 5
Change: x = 4
Then use: 4

9. More examples

Example 1: postfix increment

let number = 3;

console.log(number++);
console.log(number);
Output:
3
4

Example 2: prefix increment

let number = 3;

console.log(++number);
console.log(number);
Output:
4
4

Example 3: postfix decrement

let number = 10;

console.log(number--);
console.log(number);
Output:
10
9

Example 4: prefix decrement

let number = 10;

console.log(--number);
console.log(number);
Output:
9
9

Example 5: postfix increment with assignment

let x = 2;
let y = x++;

console.log(x);
console.log(y);
Output:
3
2

Example 6: prefix increment with assignment

let x = 2;
let y = ++x;

console.log(x);
console.log(y);
Output:
3
3

Example 7: postfix decrement with assignment

let x = 8;
let y = x--;

console.log(x);
console.log(y);
Output:
7
8

Example 8: prefix decrement with assignment

let x = 8;
let y = --x;

console.log(x);
console.log(y);
Output:
7
7

10. Increment and decrement in loops

Example: count up

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
Output:
1
2
3
4
5
i = 1 → check 1 <= 5 → true → print 1 → i++
i = 2 → check 2 <= 5 → true → print 2 → i++
i = 3 → check 3 <= 5 → true → print 3 → i++
i = 4 → check 4 <= 5 → true → print 4 → i++
i = 5 → check 5 <= 5 → true → print 5 → i++
i = 6 → check 6 <= 5 → false → stop

The loop stops because 6 <= 5 is false.

Example: count down

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
Output:
5
4
3
2
1
i = 5 → check 5 >= 1 → true → print 5 → i--
i = 4 → check 4 >= 1 → true → print 4 → i--
i = 3 → check 3 >= 1 → true → print 3 → i--
i = 2 → check 2 >= 1 → true → print 2 → i--
i = 1 → check 1 >= 1 → true → print 1 → i--
i = 0 → check 0 >= 1 → false → stop

The loop stops because 0 >= 1 is false.

11. Important note about i++ and ++i in for loops

In a simple for loop, i++ and ++i usually print the same result because the change happens after the loop body.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
for (let i = 1; i <= 5; ++i) {
  console.log(i);
}
Output:
1
2
3
4
5

But in expressions, let y = i++ and let y = ++i are different.

12. Common mistakes

Mistake 1

Thinking x++ and ++x are always the same.

let x = 5;
let y = x++;

// x = 6
// y = 5
let x = 5;
let y = ++x;

// x = 6
// y = 6

Mistake 2

Thinking x-- and --x are always the same.

let x = 5;
let y = x--;

// x = 4
// y = 5
let x = 5;
let y = --x;

// x = 4
// y = 4

Mistake 3

Forgetting that console.log prints the value at that exact moment.

let number = 5;

console.log(number++);
console.log(number);
Output:
5
6

The first console.log prints 5 because number++ uses the old value first. Then number becomes 6.

13. Mini practice with answers

let number = 5;
console.log(number++); // 5
// after that: number = 6
let number = 5;
console.log(++number); // 6
// after that: number = 6
let number = 5;
console.log(number--); // 5
// after that: number = 4
let number = 5;
console.log(--number); // 4
// after that: number = 4
let x = 10;
let y = x++;

console.log(x); // 11
console.log(y); // 10
let x = 10;
let y = ++x;

console.log(x); // 11
console.log(y); // 11
let x = 10;
let y = x--;

console.log(x); // 9
console.log(y); // 10
let x = 10;
let y = --x;

console.log(x); // 9
console.log(y); // 9

14. Final summary

12. The break operator

The break operator is used inside a loop to stop its execution.

When break is encountered inside a loop, the loop immediately ends, and control is passed to the next instruction after the loop.

The break operator is usually used together with conditional operators or comparison operators inside a loop.

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

  if (i === 5) {
    console.log("Met the number 5, interrupt the execution of the cycle");
    break;
  }
}

console.log("Log after cycle");

In this example, the for loop would normally run while i is less than 10.

But when i === 5 becomes true, break is used, and the loop stops.

Diagram 12. How break stops a loop

i = 0 → continue
i = 1 → continue
i = 2 → continue
i = 3 → continue
i = 4 → continue
i = 5 → break
        ↓
      loop stops

Explanation

break stops the loop, then JavaScript continues after the loop.

13. The break operator and functions

When break is encountered inside a loop, the loop stops immediately, even if the loop is inside a function.

That means break does not stop the function, only the loop.

function findNumber(max, target) {
  console.log("Log in the body of the function before the cycle");

  for (let i = 5; i <= max; i += 1) {
    console.log("Current counter value i:", i);

    if (i === target) {
      console.log(`Found the number ${target}, interrupt the cycle`);
      break;
    }
  }

  console.log("Log in body function after cycle");
}

findNumber(10, 6);
console.log("Log after exiting function");

Diagram 13. break inside a function

function starts
   ↓
loop starts
   ↓
target found
   ↓
break stops loop
   ↓
function continues after loop

Explanation

break only exits the nearest loop.

14. Stop the loop and function with return

To stop both the loop and the function at once and return the result to the outer code, use the return operator.

In the example below, we are searching for the number 6.

As soon as the if condition is true, we return, which stops both the loop and the function.

function findNumber(max, target) {
  console.log("Log in the body of the function before the cycle");

  for (let i = 5; i <= max; i += 1) {
    console.log("Current counter value i:", i);

    if (i === target) {
      console.log(`Found the number ${target}, we make a return, interrupting the loop and function`);
      return i;
    }
  }

  // This console.log is not executed if return happens above
  console.log("Log in body function after cycle");
}

const result = findNumber(10, 6);
console.log("Log after exiting function");
console.log(`Result of function execution ${result}`);

Diagram 14. return inside a loop function

function starts
   ↓
loop starts
   ↓
target found
   ↓
return i
   ↓
loop stops
function stops
value is returned

Explanation

return exits the whole function, so the loop stops too.

15. Quick reminder

Diagram 15. Loop tools map

Loops
│
├─ while
│  └─ check first, then run
│
├─ do...while
│  └─ run first, then check
│
├─ for
│  └─ counter-based loop
│
├─ break
│  └─ stop loop
│
└─ return
   └─ stop function

Explanation

These are the main loop tools from this note.

⬅ Back