AD JB Toolbox 01 EN

JavaScript Conditionals: if, else if, else and switch

JavaScript conditionals choose which code to run based on a condition or value. Use if for ranges and combinations of conditions, and consider switch when comparing one value with specific alternatives. The number of alternatives alone does not determine which form is clearer.

if, else if and else select one path

const score = 85;
let grade;
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}
console.log(grade); // B

An if/else if chain tests conditions in order. It executes the first matching block and skips the remaining alternatives; else handles the case where none matches. With a score of 85, the example selects B. Separate if statements can execute multiple blocks, so they are not equivalent to this chain.

Conditions interpret values as truthy or falsy. Values such as 0, an empty string, null, undefined and NaN are falsy, while "0", "false", empty arrays and empty objects are truthy. Compare input and numeric limits explicitly when truthiness would obscure your intention. MDN documents if...else evaluation.

switch compares values without type conversion

const status = "sent";
switch (status) {
  case "ready":
    console.log("Preparing");
    break;
  case "sent":
    console.log("Sent");
    break;
  default:
    console.log("Check the status");
}

A switch evaluates its expression and begins execution at the matching case. It uses strict equality semantics, so the number 1 does not match the string "1". If no case matches, execution starts at default when it exists. See the switch reference for the matching and execution rules.

Missing break causes fall-through

const color = "red";
switch (color) {
  case "red":
    console.log("Red selected");
    // Without break, execution continues into the next case.
  case "blue":
    console.log("Next case executed");
    break;
}

The output contains both "Red selected" and "Next case executed". After finding the red case, execution continues into the following case without checking its value again. This behavior is called fall-through. It can intentionally let several cases share code, but a forgotten break can also execute an unintended action.

Complete example: validate input before branching

Save the code as conditions.html in UTF-8 and open it in a browser. Input values are strings, so the example converts the value to a number and checks for blank or nonfinite input before comparing it with 10.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Conditionals: number comparison and order status</title>
  <style>
    body { margin: 24px; font: 16px/1.7 sans-serif; }
    input, button, select { font: inherit; max-width: 100%; }
    label { display: block; margin-top: 12px; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
<label for="number">Number to compare with 10</label>
<input id="number" type="text" value="20">
<label for="state">Order status</label>
<select id="state"><option value="ready">Ready</option><option value="sent">Sent</option><option value="other">Other</option></select>
<button id="check" type="button">Check result</button>
  <pre id="output" aria-live="polite"></pre>
  <script>
    function check() {
      const text = document.getElementById("number").value.trim();
      const value = Number(text);
      let comparison;
      if (text === "" || !Number.isFinite(value)) {
        comparison = "Enter a finite number.";
      } else if (value < 10) {
        comparison = "Less than 10.";
      } else if (value === 10) {
        comparison = "Equal to 10.";
      } else {
        comparison = "Greater than 10.";
      }
      let message;
      switch (document.getElementById("state").value) {
        case "ready":
          message = "Preparing the order.";
          break;
        case "sent":
          message = "The order has been sent.";
          break;
        default:
          message = "Check the order status.";
      }
      document.getElementById("output").textContent = `${comparison}\n${message}`;
    }
    document.getElementById("check").addEventListener("click", check);
    check();
  </script>
</body>
</html>

The initial value 20 produces "Greater than 10." and the ready status produces "Preparing the order." Try 10 and 5, then abc, blank input and Infinity. Invalid inputs should produce the finite-number prompt. Without validation, NaN can make both a less-than test and an equality test false, incorrectly sending execution to the final else.

Common mistakes to check

  • if (x = 10) assigns a value; it does not compare. Use a comparison operator such as ===.
  • Put narrower conditions before broader ones when an earlier match would otherwise prevent them from being reached.
  • Wrap a case in its own { ... } block if several cases declare the same let or const name.
  • For the input conversion used here, follow Number() validation rules.
More in This Category
JavaScript Conditionals: if, else if, else and switch

JavaScript Conditionals: if, else if, else and switch

Choose conditional branches with if and switch, understand strict matching and fall-through, and validate input before comparing numbers. Includes a complete browser example.

JavaScript String(): Convert Numbers to Strings

JavaScript String(): Convert Numbers to Strings

Learn how String() converts values, why string concatenation differs from addition, and when null handling or JSON serialization is needed. Compare primitive strings with new String() objects.

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

Compare rounding methods for positive and negative values, round at different positions, and distinguish floating-point arithmetic from toFixed() display formatting.

JavaScript Notes: Number Formatting, URI Encoding and Selectors

JavaScript Notes: Number Formatting, URI Encoding and Selectors

Format numbers, choose the right URI encoding function, and build query parameters safely. Includes decoding error handling, CSS selector guidance and a runnable URL example.

JavaScript Loops: while, do...while and for Compared

JavaScript Loops: while, do...while and for Compared

Compare loop execution order and behavior when the initial condition is false. Learn how break and continue work and avoid infinite loops and index boundary errors.

JavaScript Thousands Separators: Add Commas and Parse Input

JavaScript Thousands Separators: Add Commas and Parse Input

Format numbers with locale-aware thousands separators and validate grouped decimal input before converting it. Covers decimal options, string formatting and precision limits.

JavaScript Number(): Convert Strings and Validate Input

JavaScript Number(): Convert Strings and Validate Input

Convert text to numbers while rejecting blank and nonfinite input. Compare Number(), parseInt() and parseFloat(), and account for accepted formats and precision limits.