Skip to main content

switch-case in js

OK here I will show the switch case usage of js. 
This is my 6th Java Script tutorial and I have followed more basics on last 5 tutorials. You can check them in blog. https://chamzzdot.blogspot.com/
Ok let’s move on.
Switch statement
This works like if else statement. But it is more efficient and no need to code much like if else. Think you have 5 marks for your mathematics paper. This is the grade list in your college that depend on your marks. Assume that the maximum score is 6.😉
6 =A
5 =B
4 =C
3 =D
2 = E
1 = F
So you need to write js program to find your grade. For now you have to remember what you can use for that. Yes, it is if else.
See this,

Figure 1
But we can get the same result with more efficient code by using switch case. OK I will explain switch case using flow chart first.

Figure 2

Ok I will explain what the flow chart says. First we have to go inside to the switch case by having a situation (case). But inside the program there are lots of cases. So we have to go to case to case as one by one.
If one of our case is equal to the case inside the program the statement will be executed.
But there is another situation here. I will tell about it later. First see the below code.

Figure 3
OK. will clarify this code against to the definition. First I have a case with 5 marks. But the program has several cases. The cases are marks 6, 5, 4, 3, 2, 1 and there is another case called default. So if there is no any matching cases with our case the default case will execute.
So according to our case it must execute second case.
See the below image that shows the result.👉


Figure 4

Let’s move to another thing that I have hold over before.
If you have check the code properly you will see some extra thing here.
Yeh that is break statement.
Do you know why we use this break statement???
OK first try to run same code without break statement. (Just add a comment to break statement)
Look here I did it 😂😂

Figure 5
What happened there is first it check the case 1 and clarified that it didn’t match, then go the case 2 it is OK. Then execute it. But it doesn’t break after matching statement executed. So it execute all the statements after matching statement. 
So It is necessary to think twice on break statement in this kind of situations.

 Thank you all 😊 and hope to meet you with another js tutorial that describes about js function.✋



  

Comments