Summary
const myString = 'First';
switch (myString) {
case 'First':
// Insert code here
break;
case 'Second':
// Insert code here
break;
case 'Third':
// Insert code here
break;
default:
// Insert code here
}
Details
A switch
statement works by trying to match an expression passed into it to one of the cases listed inside of it.
In the example above, if myString
contained the string 'First'
, then the statements inside of the first case would be executed. Likewise, if myString
contained the string 'Second'
, then the statements inside the second case would be executed, and the pattern continues from there.
The break
keyword breaks out of the switch statement. Most cases typically end with the break
keyword, but it’s technically optional. If a case does not end with the break
keyword, then the statements inside the case next are executed until the computer encounters a break
keyword or the switch statement ends.
The statements after the default
case are executed if the expression passed in to the switch statement doesn’t match any of the other cases. If the default
statement is the last case, it does not need to end with the break
keyword.
A switch statement doesn’t have to use strings. You can use numbers as well.
const myNumber = 1;
switch (myNumber) {
case 1:
// Insert code here
break;
case 2:
// Insert code here
break;
case 3:
// Insert code here
break;
default:
// Insert code here
}
Demo
Exercises
Try the following statements in the console:
const myString = 'First';
let word;
switch (myString) {
case 'First':
word = 'First';
break;
case 'Second':
word = 'Second';
break;
case 'Third':
word = 'Third';
break;
default:
word = 'default';
}
The output should be ‘First’.