Chapter 2 Cheatsheet: Comparisons & Logic

This cheatsheet summarizes the control flow and comparison mechanics in JavaScript covered in Chapter 2. Use it as a quick reference when building your logic!

Conditionals

Control the flow of your application using standard if, else if, and else blocks.

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else {
  console.log("C or below");
}

Comparison Operators

Always prefer strict equality to avoid unintended type conversions.

  • Strict Equality (=== / !==): Compares both value and type. (e.g., 5 === "5" is false)
  • Loose Equality (== / !=): Converts types before comparing. (e.g., 5 == "5" is true. Avoid using this.)
  • Inequalities: <, >, <=, >=

Logical Operators

Combine multiple conditions together.

  • && (AND): True only if both sides are true.
  • || (OR): True if either side is true.
  • ! (NOT): Inverts the boolean value.

The Switch Statement

A cleaner alternative to long if-else chains when checking a single variable against many specific values. Always include a break to prevent fall-through execution.

switch (status) {
  case "active":
    return "Green";
  case "inactive":
    return "Red";
  default:
    return "Gray";
}

The Ternary Operator

A one-line shorthand for simple if-else statements. Best used for single-line assignments. Avoid nesting them.

// condition ? valueIfTrue : valueIfFalse
const status = retries < 10 ? "Processing" : "Failed";

Truthy and Falsy

JavaScript automatically evaluates non-boolean values as either true or false in conditionals.

The 6 Falsy Values:

  1. false
  2. 0
  3. "" (empty string)
  4. null
  5. undefined
  6. NaN

Everything else is Truthy (including empty arrays [] and negative numbers like -1).

Nullish Coalescing (??)

A concise way to provide a default fallback value specifically when a variable is null or undefined.

// If userConfig is null/undefined, default to "Standard"
const theme = userConfig ?? "Standard";