Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

switch — selecting a branch

The switch statement selects where execution begins by strictly comparing a value with case expressions. Learn how default, break, fall-through, and the shared declaration scope affect control flow.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

switch (expression) {
  case value1:
    statements;
    break;
  case value2:
    statements;
    break;
  default:
    statements;
}

switch is a reserved JavaScript keyword introducing a selection statement, not a value-producing expression. The parenthesized expression is evaluated once. case expressions are checked in source order until the first match, using === semantics without type conversion: 2 does not match "2".

Execution begins at the matching case. The optional default identifies where execution begins if no case matches; it can appear at most once and need not be last. Without a match or a default, the statement executes no branch.

Labels do not stop execution: code falls through into subsequent branches unless control is transferred elsewhere. An unlabeled break exits the nearest enclosing loop or switch statement; return exits the function. Empty branches allow several cases to share code.

Branches share the lexical scope of the switch block. Repeating a name declared with let or const in that scope causes a syntax error. Wrap individual branch bodies in {} blocks when separate scopes are needed.

Examples

function describe(value) {
  switch (value) {
    case 2:
      return "number";
    case "2":
    case "two":
      return "text";
    default:
      return "other";
  }
}

console.log(describe(2));
console.log(describe("2"));
console.log(describe("two"));
console.log(describe(3));

Result

number
text
text
other

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources