If vs. Switch Statements on JavaScript

If vs. Switch Statements on JavaScript

When to use them? Which one is better? Let's learn more about it!

·

6 min read

Deciding which conditional statement to use can be quite tricky, they both help making decisions in our code, have their own set of pros and can make your code easier to read in many cases, but before we get to compare them let's have a quick overview.

If Statements

They check for equality and logical expression(with the comparison operators). The If statements tell JavaScript to check if the condition between the parentheses is true or false and if true to execute the code in the curly braces.

Let's see the syntax:

 if (condition is true) {
 make this statement execute
}

In action it'll look a bit like:

function inAction(condition){
if(conditionIsTrue){
   return "Yes!!"
 } 
   return "No, it was false"
 }

We compare the condition using these operators:

//equality 
 if(condition == condition)

//strict equality 
 if(condition === condition)

//inequality 
 if(condition != condition)

//strict inequality 
if(condition !== condition)

//greater than
if(condition > condition)

//greater than or equal 
 if(condition >= condition)

//and 
if(condition && condition)

//less than 
 if(condition < condition)

//less than or equal 
if(condition <= condition)

//or 
if(condition || condition)

What happens when we have more than one block of code we want to execute?

If Else Statements

In the If statements when the condition is not met or false, normally nothing's going to happen but with the If Else statements we can actually set a new block of code to be executed!

Let's see the syntax:

function inAction(condition){
if(condition){
   return "Yes!!"
 } else {
   return "No, it was false"
  }
}

Now let's see an example:

function testNum(num){
if(num > 5){
  return "Bigger than 5!"
} else {
  return "It's less than 5"
 }
}

console.log(testNum(4)) //"It's less than 5"

This offers more flexibility and control over what happens in our code. But what if i have more than one condition i want to execute?

Else If Statements

You can chain If statements to execute code on more than one condition, it needs a default else statement at the end to run if all conditions are not met.

⚠️It's important to know that the function is executed from top to bottom so we need to be mindful of which statement comes first!

⚠️Also keep in mind that JavaScript will not run any other conditionals after it runs the first one that passes.

Knowing that, let's see the syntax!

function inAction(condition){
if(condition){
   return "me"
 } else if(condition2) {
   return "me instead"
  } else if(condition3){
   return "me duh!"
} else if(condition4) {
   return "me!! is this a question?"
} else{
   return "me the default value, i guess!"
 }
}

In action we'll find it a bit like this:

function testNum(num){
if(num < 5){
  return "Less than 5!"
 } else if (num < 10) {
  return "It's less than 10"
 } else if (num < 15) {
  return "It's less than 15"
 } else {
 return "Insert another number"
 }
}
console.log(testNum(9)) // "It's less than 10!"

But what if we have even more conditions in our code?

function testNum(num){
if(num < 5){
  return "Less than 5!"
 } else if (num < 10) {
  return "It's less than 10"
 } else if (num < 15) {
  return "It's less than 15"
 } else if (num < 20){
  return "It's less than 20"
 } else if (num < 25){
 return "It's less than 25"
 } else {
 return "Insert another number"
 }
}
console.log(testNum(25)) // "It's less than 25!"

Now, we can see how that can become messy quite fast, i'm sure there's a better way!

Switch Statements

Switch statements allow you execute different blocks of code based on different conditions (cases) being matched.

We can have many case statements but unlike if statements, they are executed from the first matched value until a break is specified! It checks only for equality in the values.

It will evaluate the expression once and then it's going to compare it with each case, from top to bottom.

⚠️ Switch statements use strict comparisons and for the code to be able to execute the values must be the same type!

Let's see the syntax together!

switch (expression) {
    case1:
        code to execute;
        break;
    case2:
        code to execute;
        break;
    case3:
        code to execute;
        break;
    default:
        default code;
}

⚠️If the condition turns out to be false the default statement is executed.

Default values are useful because we might not always be able to specify all the possible values and case conditions!

Think of the default statement as the last 'else' in the If Else chain we saw earlier.

var color = "blue"

switch(color){
 case "pink":
 console.log("Pink");
break;
 case "green":
 console.log("Green");
break;
 case "red":
 console.log("Red");
default:
 console.log("Other color")
} // Other Color

Multiple identical options

Switch statements can also help you have multiple options with the same output when you omit the break statement between the cases you want to 'group'.

var color = "orange"

switch(color){
case"pink":
case"red":
case"orange":
console.log("Warm tones")
break;
case"blue":
case"green":
console.log("Dark tones")
break;
default:
console.log("Muted tones")
} //Warm Tones

As you can see you can read it more clearly than the chained if else statements we saw earlier. So if you wanted to, how could you go from one to the other?

Replace If Else chains with Switch Statements

Let's do it with a visual example!

Instead of making your conditional statement like this:

if (condition == value1) {
    code to execute
} else if (condition == value2) {
    code to execute
} else if (condition == value3) {
    code to execute
} else {
    default code
}

Write it like this:

switch (condition) {
    case1:
        code to execute;
        break;
    case2:
        code to execute;
        break;
    case3:
        code to execute;
        break;
    default:
        default code;
}

I believe it's time we go over a quick comparison of the two!

Differences between If and Switch Statements

Let's evaluate some of the differences between the statements to help us make a better choice when deciding which one to use:

  • If statements check for logical expression (with the comparison operators) while Switch Statements look for strict equality between the value and the case.
  • Switch Statements are better to read and understand than a long chain of If Else's.
  • When the If statement turns out to be false the 'else' block of code will execute but in Switch Statements when the statement is false the default statement is executed immediately.
  • You need to add a 'break' on Switch Statements or the code will run until the last case.

Conclusion

There's really no reason why you shouldn't be able to use both If and Switch Statements when building projects, in fact sometimes it might be preferable to do so, rembember that most of the fun in coding is knowing that there's always more than one solution, specially when we have so many tools available. The choice is yours! The world is your oyster, my friend.

I really hope you learned something new today!

Don't hesitate to contact me and let me know if you'd like to add something else in the comments and also which one's your favorite!

Thank you for reading! :)

☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕

💙Follow me on Twitter to know more about my self-taught journey!

💜Make sure to check out more articles on my JavaScript For Newbies Series

❤️ Also subscribe to my Youtube Channel !

🖤And for more content and tips on TikTok !

Resources