Episode 1 — Fundamentals / 1.19 — Conditionals and Loops

1.19 -- Conditionals and Loops: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim before labs or interviews.
  2. Drill gaps -- reopen README.md then 1.19.a...1.19.f.
  3. Practice -- 1.19-Exercise-Questions.md.
  4. Polish answers -- 1.19-Interview-Questions.md.

Core vocabulary

TermOne-liner
TruthyAny value that coerces to true in a boolean context
Falsyfalse, 0, -0, 0n, "", null, undefined, NaN
Guard clauseEarly if + return/throw to reject invalid input immediately
Fall-throughExecution continues to next case when break is missing
SentinelSpecial value that signals loop termination
IterableObject with [Symbol.iterator]() -- arrays, strings, Maps, Sets

If / Else If / Else

if (condition1) {
  // first truthy branch wins
} else if (condition2) {
  // checked only if condition1 was falsy
} else {
  // fallback
}

Ternary: const x = cond ? valTrue : valFalse; -- single-expression only, avoid nesting.

Guard clause pattern:

function f(x) {
  if (!x) return;          // guard
  // happy path (flat)
}

Switch

switch (expr) {           // uses === (strict equality)
  case val1:
    // ...
    break;                // required -- prevents fall-through
  case val2: case val3:   // grouped cases
    // ...
    break;
  default:
    // no match
}

Remember: Wrap case bodies in { } when declaring let/const.


For loop

for (init; condition; update) { }
//   once   before     after
//          each iter  each iter
VariantIteratesBest for
for (let i = 0; i < n; i++)IndexArrays (when index needed), counted loops
for (const val of iterable)ValuesArrays, strings, Maps, Sets
for (const key in obj)Keys (strings)Plain objects only (NOT arrays)

Closure trap: var in for + closure = all see final value. Fix: use let.


While / Do-While

while (condition) { }          // 0+ iterations (checks BEFORE body)

do { } while (condition);      // 1+ iterations (checks AFTER body)

Use while when iteration count is unknown. Use do...while when at least one pass is needed.


Break / Continue / Return

StatementEffect
breakExit innermost loop (or switch)
continueSkip to next iteration of innermost loop
returnExit entire function
break labelExit the labeled loop
continue labelSkip to next iteration of the labeled loop

Warning: break inside a switch inside a for exits the switch, not the loop.

Warning: continue in while that skips the update variable = infinite loop.


Falsy values (memorize)

false | 0 | -0 | 0n | "" | null | undefined | NaN

Everything else is truthy (including [], {}, "0", "false").


Common pitfalls cheat sheet

PitfallFix
if (x = 5) (assignment)if (x === 5)
if (x === 1 || 2)if (x === 1 || x === 2)
Missing break in switchAdd break/return to every case
for...in on arrayUse for...of or classic for
var in for loop closuresUse let
continue skipping update in whilePut update before continue
Nested ternariesUse if/else or extract function
while (x !== 10) with step > 1Use while (x < 10)

Loop selection flowchart

Do you know the number of iterations?
  YES --> for loop
  NO  --> Must body run at least once?
            YES --> do...while
            NO  --> while

Iterating values of array/string?  --> for...of
Iterating keys of an object?       --> for...in (or Object.keys + for...of)
Need the index?                    --> classic for (or for...of + .entries())

Pattern quick-reference

FizzBuzz

for (let i = 1; i <= n; i++) {
  let s = "";
  if (i % 3 === 0) s += "Fizz";
  if (i % 5 === 0) s += "Buzz";
  console.log(s || i);
}

Digit extraction

while (n > 0) {
  const digit = n % 10;
  n = Math.floor(n / 10);
}

Prime check

function isPrime(n) {
  if (n < 2) return false;
  for (let i = 2; i <= Math.sqrt(n); i++) {
    if (n % i === 0) return false;
  }
  return true;
}

Search with early exit

for (const item of items) {
  if (item.id === target) { result = item; break; }
}

Master workflow

  1. Choose the right conditional (if for ranges/booleans, switch for discrete values).
  2. Choose the right loop (for = known count, while = unknown count, for...of = iterables).
  3. Flatten with guard clauses and early returns.
  4. Control flow with break (exit) and continue (skip) sparingly.
  5. Test edge cases: zero iterations, one iteration, empty input, off-by-one.

End of 1.19 quick revision.