Switch can be used instead of if else. It’s almost like if else too.
switch(expression) {
case x:
code block
break;
case y:
code block
break;
default:
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 goint to use ?

See the codes – https://github.com/nerdjfpb/javaScript-Series

Find me on social media – twitter, linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *