Search⌘ K
AI Features

The switch and with Statements

Explore how to use JavaScript switch statements as an alternative to complex if conditions to control program flow, including the effects of break and fall-through. Understand the with statement for setting the scope within an object, helping you write cleaner code when working repeatedly with the same object.

The switch statement

As an alternative to compound if statements, JavaScript defines the switch statement.

Illustration

Here is the concept explained in the form of an illustration:

Syntax #

The switch statement has the following syntax:

Node.js
switch (expression) {
case value1:
statement
break;
case value2:
statement
break;
// "case" can be repeated
case valueN:
statement
break;
default:
statement
}

The expression is evaluated, and its value is checked against values in case branches. If the value equals ...