Codectionary / Developer documentation / JavaScript

Loops: for, while, do...while

JavaScript offers several loop types. The classic for loop is ideal when you know the number of iterations, using an initializer, condition, and increment. while loops run as long as a condition remains true, checking before each iteration. do...while is similar but always runs at least once, checking the condition after the first iteration.

Syntax

for (init; condition; step) { }
while (condition) { }
do { } while (condition);

Examples

for Loop

The classic counting loop.

for (let i = 0; i < 5; i++) {
  console.log(i); // 0, 1, 2, 3, 4
}

// Looping over an array by index
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

while Loop

Looping based on a condition, checked before each pass.

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

do...while Loop

A loop that always executes at least once, since the condition is checked after.

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

// Runs at least once even if the condition starts false
let x = 10;
do {
  console.log("This runs once even though x is not < 5");
} while (x < 5);

Best practices

  • Use for...of instead of a classic for loop when you just need each value, not the index
  • Use while when the number of iterations is not known ahead of time and depends on a changing condition
  • Use do...while specifically when the loop body must run at least once regardless of the condition
  • Always ensure the loop condition will eventually become false, to avoid accidental infinite loops

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation