Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Loops: for, while, for...of, and Control Flow

Loops execute repeated logic efficiently. Choosing the right loop type improves clarity and performance.

Why this matters

Iteration appears in almost all programs for data processing, validation, rendering, and analytics.

Loop Types and Use Cases

for loop works well when iteration count is known.

while loop suits condition-driven repetition with unknown iteration count.

for...of is ideal for clean iteration over arrays and iterables.

Loop Control Statements

Use break to stop a loop early when target condition is met.

Use continue to skip only current iteration and proceed with next.

Avoid infinite loops by ensuring condition updates happen correctly.

Code Examples

for Loop with Accumulator

const nums = [10, 20, 30, 40];
let total = 0;
for (let i = 0; i < nums.length; i++) {
  total += nums[i];
}
console.log(total);

Classic loop for indexed data and aggregation.

for...of with Conditional Skip

const users = ["Asha", "", "Ravi", "Nina"];
for (const name of users) {
  if (!name) continue;
  console.log("User:", name);
}

for...of improves readability over manual indexing when index is not needed.

while for Retry Style Flow

let attempts = 0;
let success = false;
while (attempts < 3 && !success) {
  attempts += 1;
  success = attempts === 3;
}
console.log("Attempts:", attempts, "Success:", success);

while is useful for retry logic and conditional polling patterns.

Common Mistakes and Fixes

Forgetting loop condition updates

Always verify counter increments/decrements to avoid infinite loops.

Using for...in with arrays

Use for...of for array values. for...in is for object keys.

Heavy logic inside loops

Extract complex logic into helper functions for readability and testing.

Frequently Asked Questions

Which loop is best in JavaScript?

Depends on use case. for...of is readable for values, for is useful for indexed control.

Is while loop slower than for loop?

Differences are usually small. Prioritize clarity and correctness first.

Can I break from forEach?

No. Use for, for...of, or array methods like some/find for early-exit behavior.

How do I avoid infinite loops?

Ensure loop condition can become false and update loop variables correctly.

Related JavaScript Topics