JavaScript Loops in JavaScript: A Complete Overview of the Function

META

Activist
SUPREME
MEMBER
Joined
Mar 1, 2026
Messages
118
Reaction score
378
Deposit
0$
How Loops Work

Usually people don’t like repeating the same action many times in a row — after the tenth time it starts to get annoying. However, computers absolutely love performing the same actions in a loop.

For example, imagine we need to print the same line in the console ten times in a row (don’t ask why).

console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');
console.log('Hello, world!');

Yes, these are just ten identical lines. But what if we need not 10, but 100? Or 1,000? Or even 10,000? Writing them manually would definitely not be fun. For tasks like this, one of the most popular loops exists — the for loop.

for (let i = 0; i < 10; i++) {
console.log('Hello, world!');
}

The result in the console is the same, but the code only takes three lines.

The syntax of a for loop consists of three parts inside parentheses.

Initialization — let i = 0.
A counter variable i is created, which usually starts from zero.

Condition — i < 10.
As long as the condition is true, the loop continues to run. As soon as i becomes 10, the loop stops.

Step — i++.
After each iteration, the variable i increases by one.

Everything written inside the curly braces { ... } is called the loop body. This is the code that runs repeatedly.

Parentheses around the three parts are required, but curly braces are not always necessary. If the loop body contains only one line, they can be omitted:

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

In programming, counter variables are usually called i (from the word index). Sometimes j, k, and so on are used if there are multiple loops. But you can choose any variable name you like.

Now let’s move on to the definitions.

Loop — a structure that executes the same code multiple times. Each repetition of a loop is called an iteration.

Iteration — a single execution of the loop body.

The for loop is convenient when you need to work with a counter value:

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

Here we write i + 1 because the counter i starts from zero, while people usually count from one.

Loops are easy to adapt to different tasks. For example, you can change the starting and ending values by adjusting them in the counter and condition:

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

If needed, you can create a loop with a countdown, where the value of i decreases:

for (let i = 7; i > 0; i--) {
console.log(`Iteration ${i}`);
}

Another example changes the step of the counter. This can also be useful:

for (let i = 0; i <= 10; i += 2) {
console.log(`Value of i: ${i}`);
}

Loops allow you to automate routine actions and save time. Where a person would have to copy the same text hundreds of times, a loop can handle it in just a few lines of code. They are very often used when working with arrays — when you need to go through each element of a list, do something with it, and avoid writing the same code for every case.

By the way, the execution of a loop can be controlled directly while it is running. Let’s talk about that next.


---

Controlling a Loop

Let’s get straight to the point. A loop can be stopped completely or only the current iteration can be interrupted. Sometimes this is very useful.

For example, you are searching for a specific value in a long list. As soon as it is found, there is no need to continue searching. Or the opposite: you have a loop that checks elements, but some of them are not interesting, so they can simply be skipped.


---

Stopping a Loop

break is a statement that completely stops a loop, even if the continuation condition is still true. After break, the program immediately exits the loop and continues executing the code that follows.

for (let i = 1; i <= 100; i++) {
const randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(`Attempt ${i}: the number is ${randomNumber}`);

if (randomNumber === 7) {
console.log('Hooray! The number 7 appeared. Stopping the loop!');
break;
}
}

In this example, the loop stops completely when the random number equals 7. Even though the condition says i <= 100, the loop will not reach the end.


---

Ending the Current Iteration

continue ends the current iteration and immediately moves to the next one. Unlike break, it does not stop the entire loop.

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

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

In this example, the loop skips all even numbers. If i is divisible by two without a remainder, continue runs and the loop immediately proceeds to the next step.

The examples may seem a bit artificial, but knowing break and continue is very useful. With break, you can stop a loop once the desired result is found, saving time and resources. With continue, you can flexibly control the logic — filtering unnecessary cases and simplifying code.


---

The while Loop

The for loop is usually used when the number of iterations is known. However, sometimes we do not know in advance how many times an action must be repeated. We only know the condition under which the loop should continue running. That’s where the while loop comes in.

while is a loop that executes its body as long as the specified condition remains true. As soon as the condition becomes false, the loop stops.

let password = '';

while (password !== '1234') {
password = prompt('Enter the password (hint: 1234)');
}

alert('Welcome!');

A prompt window appears asking for the password. If the input is incorrect, the loop keeps asking. As soon as the user enters "1234", the condition becomes false and the loop stops. After that, a welcome message appears.

How while works

1. The condition inside the parentheses is checked.


2. If the condition is true, the loop body executes.


3. After execution, the condition is checked again.


4. The loop repeats as long as the condition remains true.



The number of repetitions is unknown in advance — the loop runs until the condition changes.

Just like other loops, while can be interrupted with break or skip iterations with continue.

It is important not to forget to change the condition inside the loop. If the condition always remains true, the loop will never stop, resulting in an infinite loop.

while (true) {
console.log('This will repeat forever!');
}

Such loops can cause a program or browser to freeze.


---

The do...while Loop

The do...while loop is very similar to while, but with one important difference. The while loop checks the condition first and then executes the loop body. The do...while loop works the other way around — it executes the body first and only then checks the condition.

do...while is a loop that runs the body at least once, and then continues as long as the condition remains true.

let randomNumber = 0;

do {
randomNumber = Math.floor(Math.random() * 6) + 1;
console.log(`Rolled: ${randomNumber}`);
} while (randomNumber !== 6);

console.log('Hooray! A six appeared!');

In this example, we generate a random number from 1 to 6. If the result is not six, the loop repeats. Once six appears, the loop stops.

The key point is that even if the correct number appears on the first attempt, the loop body still runs at least once.

How do...while works

1. The loop body executes.


2. The condition after while is checked.


3. If the condition is true, the loop runs again.


4. If the condition is false, the loop ends.



Just like with while, if the condition always remains true, the loop will never finish and will become an infinite loop.


---

Summary

We have explored the for, while, and do...while loops. Other loops such as for...of, for...in, and array methods are easier to understand after learning about arrays.

The most important thing to remember: loops allow you to automate repetitive actions and make your code simpler.
 
Top Bottom