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.
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.
You get the idea. After a while you'll have quite a big set of ifs.
You can create a map for each type that has fields as values.
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.
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.