Switch Vs Object Literals
Hello Everyone welcome to my blog 🙏. Hope you are all safe and that this blog finds you in good health ❤️.
In this blog, Let's understand some of the interesting snippets that replace the conventional switch with Object Literals which makes your code simple, cleaner and readable. I hope you enjoy reading this!!
Let’s create a function which returns fruit names on inputing numbers to it.
For Example :
1. If I enter 1, it should print me Orange
2. If I enter 2, it should print me Mango
3. If I enter 3, it should print me Banana
4. If I enter 4, it should print me Apple
5. For any other input, print unknown
So, we are good with the Problem statement, It is clear that we can use either if-else or Switch for it.
if-else is straight away eliminated because as per standard coding practices if we have more than 3 conditions it is better to go with a switch.
Note: Please use browser console for seeing the output for below snippets
Solution using switch
It is pretty much a convenient way of the solution but what if we remove break from all the cases, it prints all the cases along with default.
Isn’t it cumbersome to put a break on every case?
Although we can get rid of the break statements on cases just by returning the output still we need to put a return on each case which again is cumbersome.
To avoid this, let’s move on to the object-literal way of solving the above problem statement.
Solution using Object Literal
Although the output for 1,2,3,4 is right, we are missing out on the default statement in object literal.
Is default important?
Ofcourse it is, Default will help to handle unexpected output from the given function
How to handle it 🤔 ?
This way, we can handle default conditions.
Isn’t it simple, clean and most importantly readable? Yes, it is 🤝
Although we can use the first approach of object literal without default condition only if we are sure about the input which we pass in the function.
But It’s always good to be on the safer side
and handle the default condition 🎯.
This way Object literal can be used as a replacement for the conventional Switch statement.
Here we go, That’s it folks for this blog. Hope everyone liked it.
If you like it, give it a clap 👏 and share it with your friends.
For more exciting content on Frontend, Please do follow me 🎯.
Thanks a lot, Everyone 🙏.
Until Next time,
Happy Learning ✍️
Abhishek Kovuri, UI developer