Stop using IFs in JavaScript/React/Angular

Felipe Furlanetti
JavaScript in Plain English
2 min readNov 17, 2021

--

Photo by Nadine Shaabana on Unsplash

Stop using IFs everywhere! I know that the if logic is important in software engineering, but we can do better. Use this logic but write it like a senior engineer.

I continue to see a lot of junior engineers doing code this way:

We can also use `switch case` for this example, but I still think that the best approach for this specific case should be something like:

Both codes do the same thing, but the second one is much cleaner than the first one and it works beautifully if you use Typescript.

And now you are saying: “Yeah! But it only works because you are just printing a string”. And the answer is: Nooo! we can use it in a lot of cases, we can use it to return functions, do calculations, return React components or do lazy imports, etc. The sky is the limit!!

Why use this object mapper instead of Ifs?

  1. Make your code cleaner and easier to understand (remember, your code is not for you or the machine. Your code needs to be written so anyone can look and easily understand it)
  2. Force you to separate the logic from the data and make you put names on the vars and functions you are going to use
  3. Make really easy to add new options to your “IF”, you only add a new line to the mapper

When use ifs then?

Like everything in life we have cases that make sense doing it. For the ifs I still use if in some scenarios where we are just checking one information, like:

But if we add anyone more else if to it, I always transform it to the object mapper.

Conclusion

Programming is not only about making the code work, it's about creating something easily maintainable in a team and creating a product that your clients can trust.

Thank you for reading! 🙏

If you have something to add send it to me on Twitter and I will add it here!

More content at plainenglish.io. Sign up for our free weekly newsletter here.

--

--