In JavaScript, a switch statement can be used to perform different actions based on different conditions. The switch statement tests the value of a variable or an expression against multiple cases, and executes a block of code for the matching case.
Here is an example of how to use a switch statement in JavaScript:
switch (expression) {
case valueOne:
// code block to be executed if expression === valueOne
break;
case valueTwo:
// code block to be executed if expression === valueTwo
break;
default:
// code block to be executed if expression doesn't match any cases
}
You can have as many cases as you want and the default
is optional. In the example, the expression is evaluated, and the value is compared to the values of the case labels. When a match is found, the code block associated with that case is executed. The break statement is used to exit the switch statement once a matching case is found and its code block has been executed. Two or more cases can also have the same outcome:
switch (expression) {
case valueOne:
case valueTwo:
// code block to be executed if expression === valueOne or valueTwo
break;
default:
// code block to be executed if expression doesn't match any cases
}
An example of using the switch statement could be:
let dayOfWeek = 'saturday'
switch (dayOfWeek) {
case 'monday':
case 'tuesday':
case 'wednesday':
case 'thursday':
case 'friday':
console.log('weekday');
break;
case 'saturday':
case 'sunday':
console.log('weekend');
break;
default:
console.log('unknown dayOfWeek');
}
You can also use true with a switch statement:
let number = 1;
switch (true) {
case number < 1:
console.log('it is less than 1!');
break;
case number < 2:
console.log('it is less than 2!');
break;
case number < 3:
console.log('it is less than 3!');
break;
}
While this might seem like a hack or unusual practice to some, I have encountered this quite a few times out in the wild!
The switch statement has some drawbacks like only compares for equality, it could be slower than using if-else statements for large numbers of conditions.
That is all
I hope you found this helpful, please feel free to leave a comment down below!