Switch Statement
JavaScript Switch Statement
A switch statement is very similar to an if statement. If statements provide the possibility of attaching else if
s and an else
, which helps JavaScript handle multiple conditionals. However, an if
statement with many extra conditionals can seem excessive and difficult to read. The switch statement excels at code readability by breaking down the logic into more organized pieces.
The example below introduces the syntax and structure of a standard switch statement.
Example
<script type="text/javascript">
var x = 3;
switch(x) {
case 1: // This case condition is the same as the if conditional of if(x == 1)
document.write('Case 1.');
break;
case 2: // This case condition is the same as the if conditional of if(x == 2)
document.write('Case 2.');
break;
case 3: // This case condition is the same as the if conditional of if(x == 3)
document.write('Case 3.');
break;
case 4: // This case condition is the same as the if conditional of if(x == 4)
document.write('Case 4.');
break;
default: // This case condition is similar to the else statement
document.write('Default.');
break;
}
</script>
Result
Case 3.
Explanation
To define a switch statement, you begin with the keyword switch
and place the value in parentheses. Generally, this value will be a variable, but you can also use numbers or strings. Within the switch statement, you use keywords like case
, break
, and default
.
The keyword case
is followed by a value, usually static, like an integer or string. Similar to an if
statement, the case condition checks if the value matches, and if so, executes the statements inside the case. Statements within the case continue until a break
is defined and executed. The break
keyword indicates that the condition is over and exits the switch statement.
The default
keyword functions like an else
statement—it executes if none of the cases are true.
How It Works
In the example, the variable x
equals 3. The switch statement evaluates each case until it finds one equal to 3. It then executes the code within that case, in this instance: document.write('Case 3.');
.
While switch statements are not as commonly used as if
statements, they offer better readability and organization when handling multiple conditions, especially for simpler modifications or additions.