Concept Explanation
Two keywords give you an "escape hatch" inside any loop:
breakis the emergency exit — stop the loop completely, right now.continueis 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
for...inon arrays: It hands you string keys ("0","1") and can pick up extra inherited properties. Usefor...offor array values.break/continuein.forEach(): They don't work insideforEach— it's a function call, not a loop. Switch tofor...ofwhen you need to bail out early.- Deep nesting:
breakonly exits one loop. To leave nested loops, use a labeled break or move the logic into a function andreturn.
Best Practices
- Prefer
for...of: It's the cleanest way to walk array values, and bothbreakandcontinuework inside it. - Exit early:
breakas 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(orObject.entries), fixed count ->for.
Practice Exercises
- The Finder: Loop an array of names and
breakwhen you reach "Zara", printing how many you checked. - The Skipper: Print the numbers 1 to 20, but
continuepast every multiple of 3. - The Inspector: Use
for...into print each key and value of acarobject on its own line.