Conditionals

JavaScript · Essentials · 8 min

Every program makes decisions; writing them clearly keeps logic readable.

if runs a block when its condition is truthy, with optional else if and else branches:

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

The condition doesn't have to be a boolean; it is converted using the truthy/falsy rules. if (items.length) is a common way to say "if there are any items". Be explicit when 0 or "" are valid values, though: if (count) is false when count is 0.

The conditional (ternary) operator cond ? a : b is an expression, so it can be used inside other expressions, return statements and template literals. Keep it to simple cases; nested ternaries quickly become unreadable.

switch compares one value against several cases using strict equality (===). Execution falls through into the next case unless you break (or return), which is occasionally useful for grouping cases but usually a bug:

switch (status) {
  case "active":
  case "trial":
    allow(); break;
  default:
    deny();
}

A pattern that makes conditional code easier to read is the early return (guard clause): handle the invalid or special cases first and return, so the main logic isn't buried inside nested ifs.

For mapping a key to a value, a lookup object (const labels = { a: "Alpha", b: "Beta" }) is often cleaner than a long switch.

Example

function shippingCost(order) {
  if (!order.items.length) return 0;          // guard clause
  if (order.total >= 50) return 0;            // free shipping

  switch (order.country) {
    case "US":
      return 5;
    case "CA":
    case "MX":                                // grouped cases
      return 10;
    default:
      return 20;
  }
}

const order = { items: ["book"], total: 20, country: "CA" };
const cost = shippingCost(order);
console.log(cost === 0 ? "Free shipping" : `Shipping: $${cost}`);
// Shipping: $10

Remember

  • if converts its condition with truthy/falsy rules — be explicit when 0 or "" are valid
  • cond ? a : b is an expression; keep ternaries short
  • switch uses === and falls through without break

Watch out for

  • Forgetting break in a switch, so the next case runs too.

Check yourself

  1. const x = "1"; switch (x) { case 1: console.log("one"); break; default: console.log("other"); } — what is logged?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else