Control flow
A program runs top to bottom, one line after another. Control-flow statements change that order: a branch chooses which piece of code to run, and a loop repeats a piece of code while a condition holds.
In JavaScript a condition does not have to be a boolean: if, while and for convert it to true or false by the truthy and falsy rules, while switch compares values strictly, like ===. Both rules are covered in detail in Coercion & Operators.
Topic map
- if and else — branching on a condition, the
else ifchain, and the ternary operator as the short form. - switch — choosing a branch by value, strict comparison,
default, and fall-through withoutbreak. - Loops —
for,while,do...while: what a loop is made of and when to pick which;for...ofandfor...in. - break and continue — leaving a loop early, skipping a step, and labels for nested loops.
Common traps
| Mistake | Consequence |
|---|---|
if (x = 5) instead of if (x === 5) | Assignment: x becomes 5 and the condition is always true |
A missing break in a case | Execution falls through into the following switch branches |
switch on the string '1' with case 1: | No branch matches: switch compares strictly, without coercion |
The bound i <= arr.length | One step too many: the last array index is arr.length - 1, and the extra step reads undefined |
Forgetting to change the counter in while | The condition never becomes false — an infinite loop |
continue in while before the counter increment | The counter stops growing — an infinite loop |
break inside a forEach callback | SyntaxError: forEach cannot be stopped, use a plain loop |
Interview relevance
Conditions and loops are rarely asked about directly, but they sit inside every "what does the program print" task and every live-coding task. The interviewer watches whether you step through a loop carefully: the counter's value on each iteration, where break fires, where continue jumps.
What is usually checked:
- How many times the loop body runs and what the counter equals afterwards.
- How
whilediffers fromdo...while. - What
switchdoes withoutbreakand how it compares values. - How
breakdiffers fromcontinueand how to leave a nested loop. - How
for...ofdiffers fromfor...in.
Typical wrong answer: "continue ends the loop." In fact continue skips only the rest of the current step and the loop moves on to the next one; break is what ends the loop.