Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Conditionals: if/else, switch, and Decision Patterns

Conditional logic controls application flow based on runtime state and input values.

Why this matters

Accurate conditions are required for validation, permissions, UI rendering, and business rules.

if/else and else if Chains

if/else is ideal for branching where conditions are dynamic and expressive checks are needed.

Order matters in chained conditions. Place most specific checks before generic checks.

Guard clause style (early return) keeps complex functions easier to read.

switch for Discrete Cases

switch works well for discrete values like status codes or command routing.

Always include default for fallback behavior and safer future handling.

Use break to prevent unintended fallthrough unless fallthrough is explicit and documented.

Code Examples

if/else with Guard Clause

function accessMessage(role, active) {
  if (!active) return "Account inactive";
  if (role === "admin") return "Full access";
  if (role === "editor") return "Edit access";
  return "Read only";
}

console.log(accessMessage("editor", true));

Guard clauses simplify control flow and reduce nesting.

switch with Default

function colorByStatus(status) {
  switch (status) {
    case "success":
      return "green";
    case "warning":
      return "orange";
    case "error":
      return "red";
    default:
      return "gray";
  }
}

console.log(colorByStatus("warning"));

switch is clear for finite known values.

Conditional Rendering Label

const score = 77;
let label = "";
if (score >= 90) label = "Excellent";
else if (score >= 75) label = "Good";
else label = "Needs Improvement";

console.log(label);

Readable style for multi-tier scoring logic.

Common Mistakes and Fixes

Missing default case in switch

Always add default to avoid undefined behavior for unknown values.

Over-nested if blocks

Use guard clauses and smaller helper functions.

Wrong condition ordering

Place specific checks before broad checks.

Frequently Asked Questions

When should I use switch instead of if/else?

Use switch when matching one variable against many fixed values.

Is nested if/else bad?

Not always, but deep nesting hurts readability and maintainability.

Should I always use braces with if?

Yes, braces improve clarity and reduce accidental bugs in future edits.

How can I simplify many conditions?

Use lookup maps, helper functions, or split logic into dedicated modules.

Related JavaScript Topics