JS

Control Flow

JavaScript · 9 entries

if / else if / else

syntax
if (condition) { ... }
else if (condition) { ... }
else { ... }
example
function getDiscount(memberLevel) {
  if (memberLevel === "gold") {
    return 0.20;
  } else if (memberLevel === "silver") {
    return 0.10;
  } else {
    return 0;
  }
}
console.log(getDiscount("gold")); // 0.20

Note Conditions are coerced to boolean. Watch out for truthy/falsy gotchas: if (arr.length) works because 0 is falsy.

Ternary Operator

syntax
condition ? valueIfTrue : valueIfFalse
example
const age = 20;
const category = age >= 18 ? "adult" : "minor";
console.log(category); // "adult"

// Nested (use sparingly)
const tier = age >= 65 ? "senior" : age >= 18 ? "adult" : "minor";

Note Great for simple inline conditions. Avoid deeply nested ternaries -- they quickly become unreadable. Use if/else for complex logic.

switch Statement

syntax
switch (expression) {
  case value: ... break;
  default: ...
}
example
function getStatusText(code) {
  switch (code) {
    case 200: return "OK";
    case 301: return "Moved Permanently";
    case 404: return "Not Found";
    case 500: return "Internal Server Error";
    default:  return `Unknown (${code})`;
  }
}
console.log(getStatusText(404));
output
"Not Found"

Note Uses strict equality (===). Forgetting break causes fall-through to the next case. Using return instead of break is a clean pattern in functions.

for Loop

syntax
for (init; condition; update) { ... }
example
const items = ["apple", "banana", "cherry"];
for (let i = 0; i < items.length; i++) {
  console.log(`${i + 1}. ${items[i]}`);
}
output
"1. apple"
"2. banana"
"3. cherry"

Note Classic loop when you need the index. For simple iteration, prefer for...of. Cache .length in the initializer if the array is very large and not changing.

for...of Loop

syntax
for (const element of iterable) { ... }
example
const scores = [88, 92, 75, 100];
let sum = 0;
for (const score of scores) {
  sum += score;
}
console.log(`Average: ${sum / scores.length}`);

// Works with strings too
for (const char of "hello") {
  process(char);
}
output
"Average: 88.75"

Note Works on any iterable: arrays, strings, Maps, Sets, generators. Does NOT work on plain objects -- use Object.entries() or for...in for those.

for...in Loop

syntax
for (const key in object) { ... }
example
const theme = { primary: "#3498db", secondary: "#2ecc71", accent: "#e74c3c" };
for (const colorName in theme) {
  console.log(`${colorName}: ${theme[colorName]}`);
}
output
"primary: #3498db"
"secondary: #2ecc71"
"accent: #e74c3c"

Note Iterates over enumerable string properties, including inherited ones. Avoid for arrays (use for...of). Use Object.hasOwn() to filter inherited keys.

while and do...while

syntax
while (condition) { ... }
do { ... } while (condition);
example
// Retry until success (with limit)
let attempts = 0;
let success = false;
while (!success && attempts < 5) {
  attempts++;
  success = Math.random() > 0.7;
}
console.log(`Succeeded after ${attempts} attempt(s): ${success}`);

// do...while always runs at least once
let input;
do {
  input = prompt("Enter a number > 10:");
} while (Number(input) <= 10);

Note do...while guarantees at least one iteration. Useful for retry logic and input validation loops.

break and continue

syntax
break;     // exit loop
continue;  // skip to next iteration
example
const data = [3, -1, 7, 0, 5, -3, 9];
const positives = [];

for (const n of data) {
  if (n < 0) continue;  // skip negatives
  if (positives.length >= 3) break;  // stop after 3
  positives.push(n);
}
console.log(positives); // [3, 7, 5]

Note break exits the innermost loop. Use labeled breaks to exit outer loops: outer: for (...) { for (...) { break outer; } }

Labeled Statements

syntax
label: for (...) { break label; }
example
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

let found = null;
search: for (const row of matrix) {
  for (const cell of row) {
    if (cell === 5) {
      found = cell;
      break search;
    }
  }
}
console.log(found); // 5

Note Labels let you break/continue a specific outer loop from inside a nested loop. Rarely needed but invaluable for searching nested structures.