Skip to main content

Switch Statement

In some cases, inconveniences when reading complex if ... else branches can be avoided by using the "flatter" syntax of the switch branch statement.

The scope of switch is limited to tasks with one common question (what to compare) and many answer options (what to compare with).

Switch statement

Its syntax consists of the switch(value) block, i.e. what to compare, and many individual case value cases, i.e. what to compare with. For comparison, the strict equality operator === is used. That is, you cannot compare in terms of more or less, only in terms of equality.

switch (value) {
case value:
statements;
break;

case value:
statements;
break;

default:
statements;
}

The value in the switch (value) block is a string or number that is compared for strict equality with all values in the case value blocks in sequence, from top to bottom.

The break statement at the end of each case block is required to interrupt further checks and go directly to the code after switch when the equality test returns true.

If no values match, the default code should be executed, as in the else block for the if...else statement. To do this, after all the case blocks, a default block is added. No break statement is required after the default block, since this is the last thing that will be executed in the switch, and control will be transferred to the code after it.

let cost;
const subscription = "premium";

switch (subscription) {
case "free":
cost = 0;
break;

case "pro":
cost = 100;
break;

case "premium":
cost = 500;
break;

default:
console.log("Invalid subscription type");
}

console.log(cost); // 500
Note

If the break statement is absent, then after some case condition has been fulfilled, all subsequent blocks of code will be executed one after the other, which can lead to negative consequences if used incorrectly.