When you first writing JavaScript, you will realize that Switch
and If
statements can do about the same thing. So, why bother? 🤔
Seriously, why?
Switch
has few advantages over if
statements.
Switch
is easier to read- Easier to debug
- After getting use to, faster to write
- Requires less processing power, can improve performance on large system.
Let's see an example. This is a very simple example and can be re-written way better with minimal effort.
const pickedNumber = 5;
switch (pickedNumber) {
case 1:
console.log('picked number is = 1');
break;
case 2:
console.log('picked number is = 2');
break;
case 3:
console.log('picked number is = 3');
break;
/// default works like else statement in If
default:
console.log('number higher than 3');
break;
}
//// same code with IF statements
if (pickedNumber === 1) {
console.log('picked number is = 1');
} else if (pickedNumber === 2) {
console.log('picked number is = 2');
} else if (pickedNumber === 3) {
console.log('picked number is = 3');
} else {
console.log('number higher than 3');
}
How does it work behind the scenes?
To understand the main difference between Switch
and If / else
first, we need to understand how the computer handles them.
Imagine, we have a very long list of numbers, from 1 to 500. No, I'm not going to write it all.
With if
statements, the computer needs to check every single condition. If the statement is a complex block:
if(num > 5 && num < 20 || num <10)
the computer will do these calculations and then decide if the statement returns true
or false
.
if (number === 1) {
console.log('number is 1');
}
// imagine there are 498 more else if statements
else if (number === 500) {
console.log('number is 500');
}
Our poor computer will check every single line of code until it finds the matching condition. First, if the number
is equal to 1
, then it will check is number
is equal 2
, on an on...
if we write the same code using Switch
switch(number){
case 1:
console.log("number is 1")
break;
//many lines of code//
//many lines of code//
case 500:
console.log("number is 500)
break;
}
Computer will look at the value of number
, it will match the value with the case
number. I won't do any calculations, it will only match the value given to the case
.
Imagine working in a legal office. There are thousands of legal papers, binders, everything in paper form. They tell us to find a piece of paper that has the this number in it "123123123123123". We say cool, who's is it, could you tell me the ID of the paper or any other information that can help us find it? They say, no lol 😂 go read every single paper we have and find it your-self. That would take days to find that piece of paper.
Using Switch
statements is having the case id
of the paper we are looking for. If the paper ID (case) is AB12-12, we would know where to find that paper.
This is where the performance difference between If / Else
and Switch
comes from.
Let's dive into how Switch statement works
- We need to setup our
Switch
switch (weather) {
}
- Next, we need to define our cases;
switch (weather) {
case 'sunny':
displaySunIcon();
break;
case 'rainy':
displayRainIcon();
break;
}
We setup our cases, if the
weather
parameter issunny
, we will invokedisplaySunIcon()
function. If it'srainy
,displayRainIcon()
will be invoked.
After one of the cases are true and function is invoked,
break
keyword will break theSwitch
case and the next case won't be checked.
Think of it like, your cat is hiding somewhere and you are looking for it, when you find your cat, you will stop searching your cat. Finding your cat will
break
your search.
- Using
Break
switch (weather) {
case 'sunny':
displaySunIcon();
break;
case 'rainy':
displayRainIcon();
break;
case 'snowRain':
displaySnowIcon();
displayRainIcon();
break;
}
You know, sometimes it snows and rains at the same time. Yeah, I don't like it either 🥲. When that happens, we might want to invoke 2 functions at once.
- Let's look at
default
switch (weather) {
case 'sunny':
displaySunIcon();
break;
case 'rainy':
displayRainIcon();
break;
default:
console.log('call the developers`)
break;
}
if none of the cases match,
default
case gets invoked. It's similar to usingelse
at the end of aif
block.
You don't have to have the
default
case, but I highly suggest that you include it in everySwitch
case you write from now-on. You can use it to catch errors too, be creative.
What do you think? I find Switch
statements easier to read and debug.
When should we use Switch?
Working on a simple app, site or a project, it doesn't really matter. Use whichever you like, mix and match. Switch
being faster than If/Else
won't matter. If you ever work on a large scale app, using Switch
when needed can improve performance.
If you need to include &&, ||, >, <
for some logic, I think going for if/else
makes more sense. For boolean, true / false
conditions, If / Else
could be the proper choice.
If the condition we are testing is random but has set number of outcomes (like weather), using Switch
might make more sense. If the condition we are working with has a dominant result, going with If / Else
can be more beneficial.
Here is our weather app again, we can use
Switch
statements to display an icon depending on the weather.
switch (weather){
case "sunny":
displaySunIcon();
break;
case "rain"
displayRainIcon();
break;
case 'snowRain':
displaySnowIcon()
displayRainIcon()
break;
default:
console.log('someone call the developer, we might have a problem')
}
Fun Fact:
default
case do not require abreak
because the code block will stop regardless.
imagine a website pop-up where we need to check visitor's age
const userAge = 21
const userLocation = 'usa'
if (userLocation === 'usa' && userAge >= 21) {
console.log('user can view the website')
} else if(userLocation === 'germany' && userAge >= 18){
console.log('user can view the website)
}
Drinking age is 21 in the USA 🙄, and I think it's 18 but could be even lower in Germany. Using
If / Else
here makes sense
Closing words
If the logic is simple, there are set number of possible conditions, but they are random (like weather), try writing Switch
statements. If the logic is complex, where you need to use && || < > true false
, I think sticking with If / Else
is more practical;.