Control Flow and Loops
What this domain covers
Branching and iteration: if/else, switch, the loop forms, and the break/continue/label machinery. Items usually ask how many times a body runs or what a leaked loop variable holds afterwards.
Branching
if evaluates its condition with ToBoolean. switch compares with strict equality, so switch ('1') will not match case 1:. Without break, execution falls through into the following cases; default can appear anywhere but is only reached when no case matched (or by fall-through from an earlier case).
Loop forms
for (init; test; update)-updateruns after each iteration, before the next test.whiletests first;do...whileruns the body at least once.for...ofiterates values of iterables (arrays, strings,Map,Set).for...initerates enumerable keys, including inherited ones - the wrong tool for arrays, and it yields strings.
break leaves the loop; continue jumps to the update/test. A label lets break outer; exit nested loops.
Worked example
for (var i = 0; i < 3; i++) {}
console.log(i);
const arr = ['a', 'b'];
for (const k in arr) console.log(typeof k);
Reasoning: var is function-scoped, so i survives the loop and holds 3. for...in yields property names, which are strings, so the log prints 'string' twice. Replacing var with let would make i block-scoped and console.log(i) a ReferenceError.
Traps
- Omitting
breakinswitchand running unintended cases. - Off-by-one:
i <= arr.lengthreads one element past the end. for...inon arrays returning index strings rather than numbers.- A
constloop variable in a classicforheader fails oni++. forEachcannot be exited withbreak; usesome,find, or a real loop.