Break, Continue & Loop Choices

Break, Continue & Loop Choices in JavaScript: Two keywords give you an "escape hatch" inside any loop: is the emergency exit — stop the loop completely, right…

Concept Explanation

Two keywords give you an "escape hatch" inside any loop:

  • break is the emergency exit — stop the loop completely, right now.
  • continue is the skip button — abandon this round and jump to the next one.

JavaScript also gives you a few loop styles, and picking the right one keeps code clean: for (a counter), for...of (the values in an array), for...in (the keys of an object), and while (an unknown count).


Syntax or Core Structure

break and continue

const nums = [4, 7, -1, 9, 12];

for (const n of nums) {
  if (n < 0) continue; // skip negatives, keep looping
  if (n > 10) break;   // stop the whole loop
  console.log(n);      // prints 4, 7, 9
}

Choosing the right loop

const cart = ["book", "pen"];
for (const item of cart) console.log(item); // VALUES: "book", "pen"

const user = { name: "Al", age: 30 };
for (const key in user) console.log(key);   // KEYS: "name", "age"

Real World Example

Searching a contact list: loop through the contacts and break the moment you find the match — no reason to scan the other 5,000 names. Cleaning form data: continue past any blank rows so only real entries get saved.


Common Mistakes

  1. for...in on arrays: It hands you string keys ("0", "1") and can pick up extra inherited properties. Use for...of for array values.
  2. break/continue in .forEach(): They don't work inside forEach — it's a function call, not a loop. Switch to for...of when you need to bail out early.
  3. Deep nesting: break only exits one loop. To leave nested loops, use a labeled break or move the logic into a function and return.

Best Practices

  • Prefer for...of: It's the cleanest way to walk array values, and both break and continue work inside it.
  • Exit early: break as soon as the answer is found — it's faster and clearer than juggling a flag variable.
  • Match the tool to the data: values -> for...of, object keys -> for...in (or Object.entries), fixed count -> for.

Practice Exercises

  1. The Finder: Loop an array of names and break when you reach "Zara", printing how many you checked.
  2. The Skipper: Print the numbers 1 to 20, but continue past every multiple of 3.
  3. The Inspector: Use for...in to print each key and value of a car object on its own line.