switch
This YouTube video was created by Steve Griffith.
The switch statement
The switch
statement is similar to the if...else
, but instead of evaluating a condition, the switch
statement contains different cases. Each case
is evaluated to see if it matches the provided expression. A case
will only be match the expression and case have the exact same values using the strict comparison (===
). If a case does match the expression, the associate block of code will be executed.
A break
statement is used tell the program to jump out of switch statement and ignore the remaining cases. If a break
statement is not used than fall through will occur.
const answer = 'A'
switch (answer) {
case 'A':
// this block of code will execute
console.log('A is the wrong answer')
break
case 'B':
// this block of code will NOT execute
console.log('B is the wrong answer')
break
case 'C':
// this block of code will NOT execute
console.log('C is the correct answer')
break
}
The break statement
In most cases, it is necessary to include a break
at the end of a case
. If a break
statement is not used than fall through will occur and all remaining cases will executed. This is because once a switch
encounters a matching case
all remaining cases are also considered matches.
const answer = 'A'
switch (answer) {
case 'A':
// this block of code will execute
console.log('A is the wrong answer')
case 'B':
// this block of code will ALSO execute
console.log('B is the wrong answer')
case 'C':
// this block of code will ALSO execute
console.log('C is the correct answer')
}
When used properly, fall through can be used to make the code more efficient, by stacking cases together.
const answer = 'A'
switch (answer) {
case 'A':
case 'B':
// this block of code will execute
console.log('This is the wrong answer')
break
case 'C':
// this block of code will NOT execute
console.log('This is the correct answer')
break
}
The default clause
The default
clause, similar to the else
statement, is use to provide a default statement if no matching case
is found.
NOTE
It is best practice to set the default
clause as the last clause in a switch statement.
const answer = 'D'
switch (answer) {
case 'A':
// this block of code will NOT execute
console.log('A is the wrong answer')
break
case 'B':
// this block of code will NOT execute
console.log('B is the wrong answer')
break
case 'C':
// this block of code will NOT execute
console.log('C is the correct answer')
break
default:
// this block of code will execute
console.log('That is not a valid answer')
}