What is the purpose of break and continue?
JavaScriptThe short answer
break exits a loop entirely — no more iterations run. continue skips the current iteration and jumps to the next one. Both give you control over loop execution flow.
break
for (let i = 0; i < 10; i++) { if (i === 5) break; // exits the loop console.log(i);}// Output: 0, 1, 2, 3, 4Common use: stop searching once you find what you need:
const users = [ { name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' },];let found;for (const user of users) { if (user.name === 'Bob') { found = user; break; // no need to check the rest }}continue
for (let i = 0; i < 10; i++) { if (i % 2 === 0) continue; // skip even numbers console.log(i);}// Output: 1, 3, 5, 7, 9Common use: skip items that do not meet a condition without nesting inside if:
for (const item of items) { if (!item.active) continue; processItem(item);}In switch statements
break is also used in switch to prevent fall-through:
switch (color) { case 'red': console.log('Stop'); break; // without this, it falls through to the next case case 'green': console.log('Go'); break;}Interview Tip
Show one example of each with a for loop. Mention that break is also used in switch statements. This is a basic question — keep it short.
Why interviewers ask this
This tests fundamental control flow knowledge. It is a simple question usually asked in early-career interviews.