JavaScript Control Flow

Conditionals & Loops

Decision-making and iteration — if/else, switch, and every loop form JavaScript offers, including the ones unique to it.

ES2023 ✓ Core Concepts 2 Topics
01

Conditionals & Operators

CategoryOperatorsExample
Arithmetic+ - * / % **10 % 3 === 1, 2 ** 3 === 8
Comparison=== !== > < >= <=Prefer === / !== always
Logical&& || !age > 18 && age < 60
Nullish coalescing??input ?? "default" — only falls back on null/undefined
Optional chaining?.user?.address?.city — no crash if missing
JavaScript — switch & ternary
const day = 3;
switch (day) {
  case 1: console.log("Mon"); break;
  case 3: console.log("Wed"); break;   // runs
  default: console.log("?");
}

// Ternary — compact if/else expression
const age = 20;
const status = age >= 18 ? "adult" : "minor";
switch uses === under the hood, and cases fall through without break — a missing break is one of the most common JS bugs.
02

Loops in JavaScript

JavaScript has more loop forms than most languages because arrays, objects, and iterables all need slightly different iteration.

JavaScript — for, while, for-of, for-in
// classic for — index-based
for (let i = 0; i < 5; i++) console.log(i);   // 0 1 2 3 4

// while — condition checked first
let n = 3;
while (n > 0) { console.log(n); n--; }

// for-of — values of any iterable (arrays, strings, Maps, Sets)
const nums = [10, 20, 30];
for (const n of nums) console.log(n);

// for-in — enumerable KEYS of an object (avoid on arrays)
const user = { name: "Ada", age: 36 };
for (const key in user) console.log(key, user[key]);

// DSA example — find maximum
const arr = [3, 7, 2, 9, 5];
let max = arr[0];
for (const x of arr) { if (x > max) max = x; }
console.log(max);   // 9
for-of for values, for-in for keys. Using for-in on an array works but also walks inherited/enumerable properties — for-of or .forEach() is the safe default for arrays.

Quick Quiz

1. Without break, a switch case will…
2. Which loop iterates over object keys?
3. input ?? "default" falls back when input is…
4. user?.address?.city protects against…
5. for (let i = 0; i < 3; i++) — how many iterations?