Frontend Quick Tips #1 Map - How to Get Rid of 'If' Hell

Bernard Klatka

Apr 13, 2021 • 2 min read

No one likes those big articles - that’s why we’re creating Quick Tips - short tips to change your developer's life from the moment you read them.

Those may be some patterns explained in JS code on real-life examples or some techniques for better code.

Problem?

Sometimes you have logic that depends on many conditions/different states. You have to react differently If each condition is fulfilled.

Let's say that we have a form with sections. Each section has a different set of fields.

frontend quick tips

You get the idea. After a while you'll have quite a big set of ifs.

Solution?

You can create a map for each type that has fields as values.

frontend quick tips

Let's see - we first declared a whole set of key:value pairs, so it's easy to read which section consists of which fields. If we would like to add an additional section, we could just add another key:value pair.

Below we are just using a simple object property to reach for the selected key with:

return sectionFields[sectionName] || [];

So we could have e.g.

sectionFields['car'] 

which would just take an array from an object defined higher.

When to use it?

Whenever you see that the list of ifs could scale.

More posts by this author

Bernard Klatka

New call-to-action

Read more on our Blog


Check out the knowledge base collected and distilled by experienced professionals.