JavaScript Loops & Switch Interview Questions and Answers
Compare loop forms and switch behavior, including iteration, fall-through, break, and continue.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
Theoretical JavaScript Interview Questions
Imagine you need to send a "Happy Birthday" email to 10,000 users. You wouldn't write 10,000 lines of send-email code. A loop lets you write the logic once and repeat it as many times as needed. It keeps running a block of code as long as some condition holds true, then stops. Loops are everywhere: processing arrays, reading files line by line, polling for data, or retrying failed operations. The key is always making sure your condition eventually becomes false, or you've got an infinite loop on your hands.
The for loop is your go-to when you know exactly how many times you need to repeat something. It packs three things into one line: initialization, condition check, and update. You'll use it constantly for iterating over arrays by index, running a block a specific number of times, or counting through a range Read more . Pro tip: declare your loop variable with let, not var, to avoid the classic closure-in-a-loop bug.
The for...of loop (ES6) gives you the values directly instead of making you deal with index counters. Instead of for (let i = 0; i < arr.length; i++), you just write for (const item of arr). Cleaner and less error-prone. It works on anything iterable: arrays, strings (character by character), Maps, Sets, and even NodeLists from the DOM
Read more . One catch: it does NOT work on plain objects. For objects, you need for...in or Object.entries().
The while loop keeps running as long as its condition is true, checking before each iteration. It's perfect when you don't know upfront how many times you'll loop - like reading data until you hit the end of a stream, or retrying an operation until it succeeds Read more . The critical rule: make sure something inside the loop changes the condition, or you'll freeze the browser with an infinite loop.
Reach for a for loop when you know the count upfront, like iterating through an array or running something exactly 10 times. All the loop logic (start, stop, step) lives in one neat line:
for (let i = 0; i < 10; i++) {
// Executes 10 times
}
Use a while loop when the number of iterations depends on a condition you can't predict, like waiting for user input, polling a server, or processing data until a sentinel value appears:
while (condition) {
// Executes as long as condition is true
}
The do...while loop is the while loop's cousin with one key twist: it runs the code block first, then checks the condition. This guarantees at least one execution even if the condition is false from the start. Think of a menu prompt that should display at least once before checking if the user wants to continue Read more . In practice, do...while is less common than for or while, but it's the right tool when that "at least once" guarantee matters.
Nested loops are loops inside loops. The outer loop runs once, and the inner loop runs completely for each outer iteration. If the outer runs 10 times and the inner runs 10 times, that's 100 total iterations - and this is where performance problems sneak in. They're commonly used for working with 2D arrays, grids, or generating combinations. Be careful with nesting depth: three levels deep usually means you should refactor into separate functions.
The switch statement is a cleaner alternative to long if...else chains when you're comparing one value against many possible matches. It reads like a routing table: "if this value is A, do this; if it's B, do that" Read more . Switch uses strict equality (===) for comparisons, which catches some people off guard. It's most useful when you have 3+ discrete values to check against, like handling different action types in a reducer.
break is your emergency exit from a loop or switch block. The moment JavaScript hits it, execution jumps to the first line after the loop. It's perfect for stopping early once you've found what you're looking for - like searching an array and stopping at the first match Read more .
continue is more selective - it skips the rest of the current iteration and jumps to the next one. Use it to skip items that don't meet your criteria without nesting everything inside an if-block. For example, skip invalid entries in an array while processing the rest. Both keywords only affect the innermost loop they're inside.
The default case is your fallback when none of the other case values match - think of it like the else in an if-else chain. You should almost always include one, even if it just logs an unexpected value or throws an error, so you know when something unexpected slips through Read more.
Switch uses strict equality (===) for comparisons, which means it's case-sensitive - "apple" and "Apple" are different cases. If you're matching user input or data from an external source, normalize the case first (e.g., .toLowerCase()) before passing it to the switch, otherwise you'll end up with unmatched cases
Read more.
The key difference is when the condition is checked. A while loop checks first - if the condition is false from the start, the body never runs. A do...while loop runs the body once before checking, guaranteeing at least one execution. Use do...while when you need to run at least one iteration - like reading user input until it's valid.
Each case is a possible matching value for the switch expression - when the expression equals the case value (using strict equality), that block runs. Always end each case with break, or execution falls through to the next case, which is almost never what you want. Use a default case as a fallback for unmatched values, similar to an else.
forEach is tied to arrays and array-like objects - it can't be broken out of early and doesn't work with await properly inside async callbacks. for...of works with any iterable (arrays, strings, Maps, Sets, generators) and supports break, continue, and await. In practice, if you need early exits or async iteration, use for...of; otherwise forEach is fine for simple side effects.
A boundary such as i <= length accesses one index beyond the end of a zero-based array. Match the comparison to the intended number of iterations, commonly i < length.
break exits the nearest loop or switch, while continue skips to the next iteration of the nearest loop.
Without break, execution continues into subsequent case bodies after a match. Add break when each case should stop, or use intentional fall-through with clear grouping.
If each of two loops traverses n items, the combined work can grow proportionally to n squared. Analyze loop bounds and consider indexing or sets to avoid redundant scans.
JavaScript Practical and Coding Interview Questions
Problem: Write countVowels(text) that counts a, e, i, o, and u without regard to case. Log the count for JavaScript loops.
function countVowels(text) {
let count = 0;
for (const character of text.toLowerCase()) {
if ('aeiou'.includes(character)) count += 1;
}
return count;
}
console.log(countVowels('JavaScript loops'));