Web Development · Module 5 · Lesson 21 min read

Operators & Conditions

Always use strict equality

  • === and !== compare value and type: 5 === "5" is false.
  • == converts types first, with surprising results: 0 == "" is true, null == undefined is true. Avoid it.

Truthy and falsy

Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy, including "0", [] and {}.

Logical operators

  • && AND, || OR, ! NOT.
  • a || b returns the first truthy value: an old way to set defaults.
  • a ?? b (nullish coalescing) uses b only when a is null or undefined, so 0 ?? 10 keeps 0.
  • user?.address?.city (optional chaining) returns undefined instead of crashing when something is missing.

Conditions

JavaScript
if (score >= 90) {
  grade = "A";
} else if (score >= 75) {
  grade = "B";
} else {
  grade = "C";
}

const label = isMember ? "Member" : "Guest";   // ternary

switch

Good for many exact matches. Don't forget break.

💡 Return early to avoid deep nesting: if (!user) return;

Example

JavaScript
const score = 82;
const grade = score >= 90 ? "A" : score >= 75 ? "B" : "C";
console.log(grade);                         // B

console.log(5 === "5", 5 == "5");           // false true  ← use ===

const settings = { volume: 0 };
console.log(settings.volume || 50);         // 50  (0 is falsy — oops)
console.log(settings.volume ?? 50);         // 0   (?? keeps 0)

const user = { profile: null };
console.log(user.profile?.city ?? "Unknown city");   // Unknown city

const day = "sat";
switch (day) {
  case "sat":
  case "sun":
    console.log("Weekend 🎉");
    break;
  default:
    console.log("Weekday");
}