DEV Community

Cover image for Switch – JavaScript Series – Part 10
Muhammad Ali (Nerdjfpb)
Muhammad Ali (Nerdjfpb)

Posted on • Originally published at

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
Enter fullscreen mode Exit fullscreen mode

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 –

Alt Text

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." - []

So which one you are goint to use ?

You can see the graphical version here

Source Codes - { Check commits }

GitHub logo nerdjfpb / javaScript-Series

A tutorial for JavaScript Beginners


A tutorial for Absolute Beginners of JavaScript.

You can find the total pdf in - Here

You can check the commits to find the part by part codes.


Day 1
  • Day 1 - What is JavaScript?
Day 2
  • Day 2 - JavaScript Types?
Day 3
  • Day 3 - Javascript Types Cont.
Day 4
  • Day 4 - Javascript Types Cont.
Day 5
  • Day 5 - Javascript Comparisons
Day 6
  • Day 6 - Javascript Variables
Day 7
  • Day 7 - More About Variables
Day 8
  • Day 8 - Conditional Statement
Day 9
  • Day 9 - More Conditional Statement
Day 10
Day 11
Day 12
Day 13
Day 14
Day 15
Day 16
Day 17

Originally it published on nerdjfpbblog. You can connect with me in twitter or linkedin!

Top comments (0)