JavaScript Conditional Statements

Conditional statements control the flow of your program by executing different code blocks based on conditions. JavaScript provides several ways to make decisions in your code.

Types of Conditional Statements

JavaScript has four main conditional constructs: if/else, switch, ternary operator, and logical operators for short-circuit evaluation.

StatementBest ForExample Use Case
if...else1-3 conditionsCheck age range
else ifMultiple ranges/conditionsGrade calculation
switchMany exact matchesDay of the week
ternarySimple true/false assignmentsSet status text
&&, ||Short-circuit defaultsDefault values
Overview of All Conditional Types
let score = 85;

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

// Ternary
let passed = score >= 60 ? "Pass" : "Fail";
console.log(passed); // "Pass"

// Switch
let day = "Monday";
switch (day) {
  case "Monday": console.log("Start of week"); break;
  case "Friday": console.log("Almost weekend"); break;
  default: console.log("Regular day");
}

When to Use if vs switch

Use if/else when testing ranges, complex conditions, or boolean expressions. Use switch when comparing a single value against many specific options.

if vs switch
let status = "active";
let temperature = 35;

// Use if for ranges and complex conditions
if (temperature > 30 && status === "active") {
  console.log("Warning: High temp while active");
}

// Use switch for exact value matching
switch (status) {
  case "active":
    console.log("System is running");
    break;
  case "paused":
    console.log("System is paused");
    break;
  case "stopped":
    console.log("System is stopped");
    break;
  default:
    console.log("Unknown status");
}

Truthy and Falsy Values

Every value in JavaScript is either truthy or falsy. When used in a condition, truthy values evaluate to true and falsy values evaluate to false. Understanding this is key to writing clean conditionals.

Falsy ValuesTruthy Values (Examples)
falsetrue
042 (any non-zero number)
-0"hello" (any non-empty string)
"" (empty string)[] (empty array)
null{} (empty object)
undefinedfunction() {}
NaNInfinity
Truthy and Falsy in Conditions
// Falsy values
if (0) console.log("never");
if ("") console.log("never");
if (null) console.log("never");
if (undefined) console.log("never");
if (NaN) console.log("never");

// Truthy values (even empty arrays and objects!)
if ([]) console.log("empty array is truthy!");
if ({}) console.log("empty object is truthy!");
if ("0") console.log("string '0' is truthy!");

// Common pattern: check if array has items
let items = [1, 2, 3];
if (items.length) {
  console.log(`Found ${items.length} items`);
}

Guard Clauses

A guard clause is a pattern where you handle edge cases early and return, keeping the main logic un-nested. This makes code more readable.

Guard Clause Pattern
function processUser(user) {
  // Guard clauses handle edge cases first
  if (!user) {
    console.log("No user provided");
    return;
  }
  if (!user.name) {
    console.log("User has no name");
    return;
  }

  // Main logic (not nested)
  console.log(`Processing: ${user.name}`);
}

processUser(null);             // "No user provided"
processUser({});               // "User has no name"
processUser({ name: "Alice" }); // "Processing: Alice"
📝 Note: Empty arrays [] and empty objects {} are truthy! To check if an array is empty, use array.length === 0. To check if an object is empty, use Object.keys(obj).length === 0.
Exercise:
Which of these values is truthy?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.