JavaScript Loops

for Loop

Basic Structure

for (initialzation; condition; update) {
    // code block
}

Example

Outputs numbers 0 through 4.

Loading...
Output:

while Loop

Basic Structure

while (condition) {
    // code block        
}

Example

Loading...
Output:

do-while Loop

Basic Structure

do {
    // code block
} while (condition)

Example

Runs the block at least once before checking the condition.

Loading...
Output:

for...of Loop

Best for iterating through arrays or strings.

Loading...
Output:

for...in Loop

Used for iterating over object properties.

Loading...
Output:

break and continue

for (let i = 0; i < 5; i++) {
  if (i === 3) break;     // stops the loop
  if (i === 1) continue;  // skips iteration
  console.log(i);
}

Prints 0, 2.

Best Practices

  • Use for...of for arrays and strings
  • Use while when the end condition is unknown
  • Avoid unnecessary break and continue to maintain readability

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic