Last updated on Jun 2, 2021 by Suraj Sharma
In this tutorial, you will learn to write multiple OR conditions with a switch-case
statement in JavaScript
Suppose you have multiple OR
conditions in a if
statement which you want to replaced with a switch
statement.
if (value === 1 || value === 3 || value === 5) {
...
} else {
...
}
The basic usage of switch
statement is to replace lengthy if-else-if
statement with a more readable case
statements and a default
statement.
But a single case
statement does not support OR
conditions like
// not supported
switch value {
case 1 || 3 || 5:
console.log("odd number");
break;
default:
break;
}
The above example does not work because the switch
statement can only have one value per case
.
To implement multiple conditions in a switch
statement you have to write multiple case
with conditions without a break;
statement.
switch value {
case 1:
case 3:
case 5:
console.log("odd number");
break;
default:
break;
}
// equivalent to
if (value === 1 || value === 3 || value === 5) {
console.log("odd number");
} else {}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.