I am starting a new mini series on JavaScript. I’m starting it from zero. Anyone can start learning from here. My goal is helping others while learning! I know about JavaScript and I’m working on a MERN tech stack. But I think it is not a bad idea to revise the JavaScript from scratch and helping others in this time. If you have any questions, shoot on the comment session or you can directly ask me in my social media. Social media links are in the last part of today’s lesson! Let’s learn JavaScript together.

Switch — JavaScript Series — Part 10

Switch can be used instead of if else. It’s almost like if else too.

switch(expression) {
case x:
code block
case y:
code block
code block

First we need to write the switch then expression, this is mean on which variable you are trying to apply.

Cases are the specific if. Like case “todoroki” will be same of variable===”todoroki”

Let’s try the last code in switch.

First we need the variable name. Then we’ll write the switch for the name — switch(name) {} everything will go inside the second brackets.

Finally –

This is almost same right ? So which one we should use ?

As it turns out, the switch statement is faster in most cases when compared to if-else, but significantly faster only when the number of conditions is large. The primary difference in performance between the two is that the incremental cost of an additional condition is larger for if-else than it is for switch. Therefore, our natural inclination to use if-else for a small number of conditions and a switch statement for a larger number of conditions is exactly the right advice when considering performance.
Generally speaking, if-else is best used when there are two discrete values or a few different ranges of values for which to test. When there are more than two discrete values for which to test, the switch statement is the most optimal choice. [oreilly.com]

So which one you are going to use ?

Originally it published on nerdjfpb blog. Check the git for codes.

you can connect with me in twitter, linkedin or instagram



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Muhammad Ali

Muhammad Ali

An otaku who loves computer. Love to write and help others through my work. Have a look on my Instagram https://www.instagram.com/nerd_jfpb/