JavaScript Cheatsheet

Control Flow

Use this JavaScript reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

if / else if / else

if (x > 0) {
  console.log("positive");
} else if (x < 0) {
  console.log("negative");
} else {
  console.log("zero");
}

// Single-statement (braces optional but recommended)
if (condition) doSomething();

// Ternary — inline if/else
const label = x > 0 ? "positive" : "non-positive";

// Nested ternary (avoid deep nesting)
const sign = x > 0 ? "pos" : x < 0 ? "neg" : "zero";

switch

switch (day) {
  case "Mon":
  case "Tue":
  case "Wed":
  case "Thu":
  case "Fri":
    console.log("weekday");
    break;
  case "Sat":
  case "Sun":
    console.log("weekend");
    break;
  default:
    console.log("unknown");
}

switch uses strict equality (===). Always add break unless fall-through is intentional.

// Fall-through example
switch (n) {
  case 3:
    console.log("three");
    // falls through
  case 2:
    console.log("two or three");
    break;
}

// Return inside switch (no break needed)
function classify(n) {
  switch (true) {
    case n < 0:  return "negative";
    case n === 0: return "zero";
    default:     return "positive";
  }
}

for

for (let i = 0; i < 5; i++) {
  console.log(i); // 0 1 2 3 4
}

// Counting down
for (let i = 4; i >= 0; i--) { /* ... */ }

// Skip iteration
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue; // skip evens
  console.log(i);             // 1 3 5 7 9
}

// Exit early
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0 1 2 3 4
}

// Multiple variables
for (let i = 0, j = 10; i < j; i++, j--) { /* ... */ }

while / do...while

// while — condition checked before each iteration
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

// do...while — body executes at least once
let input;
do {
  input = prompt("Enter a number:");
} while (isNaN(Number(input)));

for...of (ES6)

Iterates over values of any iterable (arrays, strings, Sets, Maps, generators).

const arr = [10, 20, 30];
for (const val of arr) {
  console.log(val); // 10 20 30
}

// With index via entries()
for (const [i, val] of arr.entries()) {
  console.log(i, val); // 0 10, 1 20, 2 30
}

// Strings
for (const char of "hello") {
  console.log(char); // h e l l o
}

// Sets
for (const val of new Set([1, 2, 3])) { /* ... */ }

// Maps
for (const [key, val] of new Map([["a", 1]])) { /* ... */ }

// break / continue work inside for...of
for (const x of arr) {
  if (x === 20) break;
}

for...in

Iterates over enumerable property keys of an object (including inherited). Primarily for plain objects; avoid for arrays.

const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
  if (Object.hasOwn(obj, key)) { // skip inherited props
    console.log(key, obj[key]);
  }
}

// Pitfall with arrays — keys are strings "0", "1", ...
const arr = [10, 20];
for (const i in arr) console.log(typeof i); // "string"

Labels

// Label + break — exit a specific outer loop
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break outer;
    console.log(i, j);
  }
}

// Label + continue — jump to next outer iteration
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer;
    console.log(i, j);
  }
}

Logical Short-Circuit as Control Flow

// Execute only if condition is truthy
isLoggedIn && showDashboard();

// Fallback value
const name = user.name || "Anonymous";

// Nullish fallback (only null/undefined)
const port = config.port ?? 3000;

// Optional chaining — short-circuits on null/undefined
user?.profile?.avatar?.url;

Nullish Coalescing vs OR

// || uses falsy check (0, "", false trigger fallback)
0  || "default"   // "default"  ← might be wrong
"" || "default"   // "default"  ← might be wrong

// ?? uses nullish check (only null/undefined trigger fallback)
0  ?? "default"   // 0          ← correct
"" ?? "default"   // ""         ← correct
null ?? "default" // "default"  ← correct

Exception-Based Flow

try {
  riskyOperation();
} catch (err) {
  if (err instanceof TypeError) {
    // handle type error
  } else {
    throw err; // re-throw unknown errors
  }
} finally {
  cleanup(); // always runs
}

(See the Error Handling cheatsheet for full coverage.)

Conditional Patterns

// Guard clause / early return
function process(value) {
  if (!value) return null;      // guard
  if (value < 0) return 0;     // guard
  return value * 2;             // main logic
}

// Switch alternatives with object map
const actions = {
  add:    (a, b) => a + b,
  sub:    (a, b) => a - b,
  mul:    (a, b) => a * b,
};
const result = actions[op]?.(a, b) ?? "unknown op";

// Conditional chaining
const isAdmin = user?.roles?.includes("admin") ?? false;