Switch case can be used in the case of the if…else if…else statement. But it can only be used if all the if or else…if part depends on the value of a single variable.
Consider the below example of Javascript switch case.
var grade='D'; switch (grade) { case 'A': console.log("Great Job"); break; case 'B': console.log("Pretty good"); break; case 'C': console.log("Passed"); break; case 'D': console.log("Just Passed"); break; case 'F': console.log("Failed"); break; default: console.log("Unknown Grade"); }
// Just Passed
As we can see from the above example, the switch case depends on the value of a single variable i.e. grade. The grade can be A, B, C, D, F or some junk value entered by a user.
In the above example, we set the grade to D, so inside the switch statement case 'A', case 'B' and 'C' are checked and they are not true. Then when it encounters case 'D' it gets matched and Just Passed get prints. The break statement after that is very important as it stops the further execution of switch and it breaks or comes out of it. So, case 'F' and default statements won’t be checked.
To check the importance of break, let’s remove it from case 'D' and case 'F' in the above example and run it. You can see in the output that all three console log of Just Passed, Failed and Unknown Grade get printed
var grade='D'; switch (grade) { case 'A': console.log("Great Job"); break; case 'B': console.log("Pretty good"); break; case 'C': console.log("Passed"); break; case 'D': console.log("Just Passed"); case 'F': console.log("Failed"); default: console.log("Unknown Grade"); } // Just Passed // Failed // Unknown Grade
We can use the above logic of break to our advantage, to create some cases which just pass through. Suppose in the above example, we want grade A, B, C to print Good Job and grade D and F to print Bad Job. We can do it by below.
var grade='D'; switch (grade) { case 'A': case 'B': case 'C': console.log("Good Job"); break; case 'D': case 'F': console.log("Bad Job"); break; default: console.log("Unknown Grade"); } // Bad Job
I have learned many things from this article. It is beneficial for me. Thank you!
Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..
This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.
Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.
You have shared great information with me i appreciate your work!
Build various types of web applications,command-line application,etc....
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *