JavaScript Conditionals

📚 Lesson 4 of 22  •  ⏱ 10 min read  •  Beginner

if / else

JavaScript
const score = 75;

if (score >= 90) {
  console.log("A grade");
} else if (score >= 75) {
  console.log("B grade");
} else if (score >= 60) {
  console.log("C grade");
} else {
  console.log("Fail");
}
// Output: "B grade"

Truthy and Falsy Values

JavaScript
// Falsy values — treated as false in if conditions
if (false)     { } // false
if (0)        { } // 0
if ("")       { } // empty string
if (null)     { } // null
if (undefined){ } // undefined
if (NaN)      { } // NaN

// Everything else is truthy
if ("hello") { } // truthy
if (42)      { } // truthy
if ([])      { } // truthy (empty array is truthy!)
if ({})      { } // truthy (empty object is truthy!)

switch Statement

JavaScript
const day = "Monday";

switch (day) {
  case "Monday":
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
  case "Friday":
    console.log("Weekday");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  default:
    console.log("Unknown");
}
// Always use break — without it, execution falls through to next case

Guard Clauses — Cleaner Code

JavaScript
// Bad — deeply nested
function processOrder(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.paid) {
        // actual logic here
      }
    }
  }
}

// Good — guard clauses return early
function processOrder(order) {
  if (!order) return;
  if (order.items.length === 0) return;
  if (!order.paid) return;

  // actual logic here — no nesting needed
}

Optional Chaining (?.)

JavaScript
const user = null;

// Without optional chaining — crashes
user.address.city  // TypeError: Cannot read properties of null

// With optional chaining — returns undefined safely
user?.address?.city  // undefined (no error)

// Combine with ?? for default
const city = user?.address?.city ?? "Unknown";