~/hackweb.dev
JavaScript Iteration & Flow Control
Quiz
...

JavaScript Iteration & Flow Control

beginner · updated Tue Sep 08 2026Contribute

Master for...of, for...in, break, continue, and labels.

JavaScript Iteration & Flow Control

Beyond basic loops, JavaScript offers specialized iteration methods and flow control statements.

for...of — Arrays & Iterables

The simplest way to iterate over arrays:

let fruits = ["apple", "banana", "orange"];

for (let fruit of fruits) {
  console.log(fruit);
}
// Output: apple, banana, orange

Works on arrays, strings, Maps, Sets, and any iterable object.

for...in — Object Keys

Used specifically for iterating over object properties:

let person = { name: "John", age: 25, city: "NYC" };

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
// name: John, age: 25, city: NYC

Remember: Use hasOwnProperty to avoid inherited prototype properties.

break — Exit Early

let numbers = [1, 2, 3, 4, 5];

for (let num of numbers) {
  if (num === 3) {
    console.log("Found 3!");
    break;
  }
}
// Output: 1, 2, Found 3!

continue — Skip Iteration

for (let i = 0; i < 10; i++) {
  if (i % 2 !== 0) continue;
  console.log(i);  // 0, 2, 4, 6, 8
}

Labels — Break Nested Loops

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break outer;
    console.log(`${i}, ${j}`);
  }
}
// Output: 0,0 0,1 0,2 1,0

Without labels, break only exits the innermost loop.

Complete Example: Count Vowels

let text = "Hello World";
let vowels = "aeiouAEIOU";
let count = 0;

for (let char of text) {
  if (vowels.includes(char)) {
    count++;
  }
}

console.log(`Vowels: ${count}`);  // 3

Complete Example: Find First Match

let numbers = [1, 3, 5, 8, 9, 10];
let firstEven = null;

for (let num of numbers) {
  if (num % 2 === 0) {
    firstEven = num;
    break;
  }
}

console.log(firstEven);  // 8

Best Practices

  1. Use for...of for arrays — Cleaner syntax
  2. Use for...in for objects — Iterate over keys
  3. Use break for early exit — Don’t iterate unnecessarily
  4. Use continue to skip — Avoid nested if/else
  5. Use labels sparingly — Can be confusing

Common Mistakes

  1. Using for...in on arrays — Use for...of instead
  2. Forgetting hasOwnProperty — Gets prototype properties
  3. Breaking wrong loop — Use labels for nested
  4. Overusing continue — Can make code hard to read
  5. Not checking empty arrays — Always check length first