JavaScript Iterations

Visualizing different looping constructs and their behavior.

`for`, `while`, `do...while`

The core looping statements. The `for` loop is ideal for a known number of iterations. The `while` loop continues as long as a condition is true. The `do...while` loop is similar, but it **always executes at least once** before checking the condition.

for (let i = 0; i < 5; i++) { ... }
while (i < 5) { ... }
do { ... } while (i < 5);

Click a button to see the loop run. Watch the output.

Loop Type:

Result:


`for...in` vs `for...of`

These specialized loops simplify iteration. The **`for...of`** loop iterates over **iterable** values (like arrays and strings). The **`for...in`** loop iterates over **enumerable properties** of an object, including inherited ones.

const array = ['a', 'b'];
for (const item of array) {
  console.log(item); // 'a', 'b'
}

const obj = { x: 1, y: 2 };
for (const prop in obj) {
  console.log(prop); // 'x', 'y'
}

Observe the difference between iterating over an array and an object.

Data: `['apple', 'banana', 'cherry']`

Data: `{ a: 1, b: 2, c: 3 }`


`for await...of`

This loop is used to iterate over **asynchronous iterable** objects. It pauses and waits for each item to be resolved before moving to the next. This is essential for streams of data or async generators.

async function* asyncGenerator() {
  yield Promise.resolve(1);
  yield Promise.resolve(2);
}
for await (const value of asyncGenerator()) {
  // ...
}

Simulating an async generator that yields a value every second.

Status: Ready