How to write non-traditional switch…case

Tram Ho

I don’t know about you, but every time I write a certain line of code, I think: “Have I written code like this to clean the code?”, “Will my code make someone swear? “.

Of course, everyone will have different styles and preferences for coding, but in general, it is advisable to follow the principle of readability and understanding as much as possible.

What is a switch case block?

This command block has an extremely simple task, explaining that the “sorry to fill” type is that it takes input and corresponds to it an output. To make it easier to imagine, this command block is like a traffic flow picture: motorbikes go to the motorbike stream, cars go to oto.vv.

Here is an example of a code using

The problem of the switch block

In general, there is nothing wrong with using the switch…case statement. But sometimes, you will find the switch case block is endless, like below.

So what should we do? Is there a better coding solution? With problems like this, what do you use if you don’t use a switch case? The author is joking again!

Hihi. Of course there are alternatives. That is using Object literal lookup

Object Literal lookups

With Javascript in particular, we use Object everywhere, all the time. So why don’t we apply Object in this case. Using Object gives us a more familiar look because statistically, using Object and Array takes up the most of our code.

Ok, going back to the lengthy handleKeyUp() function above, we can rewrite it like this:

The simple solution is that we put the conditions in an Object. Object lookups are very fast, especially as they grow in size over time.

In addition, with the above method, every time you have to add a new condition, you do not need to modify the logic of the handleKeyup() function, but simply add it in the Object (no logic here at all).

What do you think of this new solution? Does it match your coding style? Please leave a comment below for everyone to share.

Reference source:

Share the news now

Source : Viblo