JavaScript Conditional Statements: if, else, switch & Ternary Operators

JavaScript Conditional Statements: if, else, switch & Ternary Operators

Once you understand JavaScript operators, the next step is learning how to make your code respond to different situations. That's where JavaScript conditional statements come in. Conditionals let your program make decisions — showing a discount to logged-in users, validating a form, or changing what renders on a page based on data. In this guide, we'll walk through every major type of conditional statement in JavaScript, with practical examples, common mistakes, and best practices for writing clean decision logic.

What Are Conditional Statements?

Conditional statements let your code execute different blocks depending on whether a condition evaluates to true or false. They're built on top of comparison and logical operators — if you haven't already, it's worth reviewing JavaScript Operators first, since conditionals rely heavily on expressions like ===, >, &&, and ||.

Why Conditional Statements Matter

Conditionals are what make your code dynamic instead of static. They let you:

The if Statement

The if statement is the most basic form of conditional logic. It runs a block of code only if a specified condition is truthy.

let age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}

If the condition is falsy, the block is simply skipped and execution continues after it.

if...else

The if...else statement adds a fallback block that runs when the condition is false.

let age = 15;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}
// Output: "You are a minor."

else if: Handling Multiple Conditions

When you need to check more than two possibilities, chain conditions together with else if.

let score = 72;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}
// Output: "Grade: C"

JavaScript evaluates each condition in order and stops at the first one that's true. Once a match is found, the remaining else if blocks are skipped entirely.

The switch Statement

When you're comparing a single value against many possible exact matches, a switch statement is often cleaner than a long if...else if chain.

let day = "Tuesday";

switch (day) {
  case "Monday":
    console.log("Start of the work week.");
    break;
  case "Tuesday":
    console.log("Second day in.");
    break;
  case "Friday":
    console.log("Almost the weekend!");
    break;
  default:
    console.log("Just another day.");
}
// Output: "Second day in."

Don't Forget break

Each case needs a break statement, or JavaScript will "fall through" and keep executing the next case's code, even if it doesn't match.

let fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("It's an apple.");
  case "banana":
    console.log("It's a banana.");
    break;
  default:
    console.log("Unknown fruit.");
}
// Output:
// "It's an apple."
// "It's a banana."   (fall-through, because "apple" has no break)

Fall-through is sometimes used intentionally — for example, to group multiple cases that share the same logic — but it's a common source of bugs when it's accidental.

Grouping Cases Intentionally

let month = "June";

switch (month) {
  case "June":
  case "July":
  case "August":
    console.log("Summer");
    break;
  case "December":
  case "January":
  case "February":
    console.log("Winter");
    break;
  default:
    console.log("Some other season");
}
// Output: "Summer"

The Ternary Operator: A Compact Conditional

For simple two-outcome conditions, the ternary operator (? :) lets you write an if...else in a single line.

let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"

The syntax follows condition ? valueIfTrue : valueIfFalse. Ternaries are especially useful for assigning a value based on a condition, but avoid nesting more than one or two levels deep — beyond that, readability suffers and a regular if...else is usually clearer.

// Getting hard to read:
let category = age < 13 ? "Child" : age < 18 ? "Teen" : age < 65 ? "Adult" : "Senior";

// Clearer as if...else if:
let category;
if (age < 13) {
  category = "Child";
} else if (age < 18) {
  category = "Teen";
} else if (age < 65) {
  category = "Adult";
} else {
  category = "Senior";
}

Truthy and Falsy Values

Conditions in JavaScript don't need to be strict booleans — any value is evaluated as either "truthy" or "falsy." Understanding this is essential for writing accurate conditionals. If you need a refresher on values and types first, read JavaScript variables and data types.

Falsy values (there are only a handful):

  • false
  • 0 and -0
  • "" (empty string)
  • null
  • undefined
  • NaN

Everything else — including "0", "false" (as strings), empty arrays [], and empty objects {} — is truthy.

if ("") {
  console.log("This won't run.");
}

if ("0") {
  console.log("This WILL run, because a non-empty string is truthy.");
}

if ([]) {
  console.log("This WILL run, because an array, even empty, is an object and truthy.");
}

Combining Conditions with Logical Operators

Conditional statements are often paired with logical operators (&&, ||, !) to check multiple conditions at once.

let age = 25;
let hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("Entry allowed.");
}

let isWeekend = false;
let isHoliday = true;

if (isWeekend || isHoliday) {
  console.log("No work today.");
}

Practical Example: Form Validation

Here's how conditional statements come together in a real-world scenario — validating a signup form (if you want to build the form markup itself first, see HTML Forms: Input Types and Validation):

function validateSignup(username, password, age) {
  if (!username || username.length < 3) {
    return "Username must be at least 3 characters.";
  }

  if (!password || password.length < 8) {
    return "Password must be at least 8 characters.";
  }

  if (age < 13) {
    return "You must be at least 13 years old to sign up.";
  }

  return "Signup successful!";
}

console.log(validateSignup("jo", "securepass123", 25));
// "Username must be at least 3 characters."

console.log(validateSignup("john_doe", "securepass123", 25));
// "Signup successful!"

This pattern — often called a "guard clause" — checks for invalid conditions early and returns immediately, which keeps the rest of the function free of deep nesting.

Common Mistakes with Conditional Statements

1. Using Assignment Instead of Comparison

let x = 5;

if (x = 10) {   // Bug: single = assigns, doesn't compare
  console.log("This always runs, and x is now 10.");
}

if (x === 10) {  // Correct: strict equality check
  console.log("This is the correct comparison.");
}

2. Forgetting break in switch Statements

As shown earlier, a missing break causes unintended fall-through. Always double-check each case unless fall-through is intentional. When a conditional doesn't behave the way you expect, our guide to JS debugging techniques shows how to trace which branch actually ran.

3. Overly Nested Conditionals

// Hard to read:
if (user) {
  if (user.isActive) {
    if (user.age >= 18) {
      console.log("Access granted.");
    }
  }
}

// Cleaner with combined conditions:
if (user && user.isActive && user.age >= 18) {
  console.log("Access granted.");
}

4. Comparing to true or false Explicitly

let isValid = true;

// Unnecessary:
if (isValid === true) {
  console.log("Valid!");
}

// Cleaner:
if (isValid) {
  console.log("Valid!");
}

Best Practices for Writing Conditionals

  • Use strict equality (===) in conditions to avoid unexpected type coercion.
  • Use guard clauses to handle invalid or edge cases early, instead of wrapping your main logic in nested if blocks.
  • Keep ternaries simple — reserve them for single, straightforward conditions.
  • Use switch for many exact-value comparisons against a single variable, and if...else if for range checks or complex conditions.
  • Name your booleans clearly (isActive, hasPermission) so conditions read like plain English. More habits like this are covered in Clean JS Code: JavaScript Best Practices for Readable Code.

Conclusion

Conditional statements are the decision-making backbone of JavaScript. Whether you're using a simple if statement, chaining multiple else if blocks, reaching for a switch, or writing a compact ternary, the goal is always the same: make your code respond intelligently to different situations. Combine this with a solid understanding of JavaScript Operators, and you'll have everything you need to build real decision logic into your applications.

Next step: try rewriting a nested if block from one of your own projects using guard clauses, or practice converting a long if...else if chain into a switch statement to see which reads more clearly. Then keep going with JS loops (for, while, forEach) and JavaScript functions, or browse every tutorial in the JavaScript category.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Your comment will appear after moderation.