Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Loops

A loop repeats the same code several times. You need one to process a list of products, print table rows or add up a total — without a loop you would have to copy the code by hand. One run of the loop's code is called an iteration.

while

The while loop repeats a block as long as the condition is true. The condition is checked before each iteration:

let i = 1;
 
while (i <= 3) {
  console.log(i);
  i++;
}
// 1
// 2
// 3

The variable i is called a counter. It must change inside the loop, otherwise the condition never becomes false.

for

When the number of repetitions is known in advance, for is more convenient. Its parentheses hold three parts separated by semicolons: the counter's starting value, the condition and the step:

for (let i = 1; i <= 3; i++) {
  console.log(`Step ${i}`);
}
// Step 1
// Step 2
// Step 3

This loop does the same as the while above, but all the counter handling is gathered in one line.

A different step

The counter does not have to grow by one. You can increase it by any number or decrease it — for a countdown, for example:

for (let i = 3; i > 0; i--) {
  console.log(i);
}
console.log('Go!');
// 3
// 2
// 1
// Go!

for...of

The for...of loop goes through items one by one: the characters of a string or the elements of an array. On each iteration the next item goes into the variable:

for (const letter of 'cat') {
  console.log(letter);
}
// c
// a
// t

No counter is needed: the loop ends by itself when the items run out. for...of works the same way with arrays — more on that in the arrays chapter.

Accumulating a result

A common technique is to create a variable before the loop and change it on every iteration. This is how totals and counts are calculated and strings are built:

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

Note that console.log comes after the loop, so only the final result is printed.

do...while

The do...while loop runs the block first and checks the condition afterwards. So the body runs at least once, even if the condition is false from the start:

let attempts = 5;
 
do {
  console.log(`Attempt ${attempts}`); // Attempt 5
  attempts++;
} while (attempts < 3);

This loop is rarely needed — for example, when you have to do something first and then decide whether to repeat it.

Common mistake

If you forget to change the counter, you get an infinite loop: the condition is always true, and the program never stops by itself:

let i = 1;
 
while (i <= 3) {
  // forgot i++ — the loop never ends
}

On this site such code is stopped after a few seconds, but on a normal page an infinite loop freezes the browser tab.

Thanks for reading!

Donate to the site — we work hard for you.