DEV Community

Cover image for Don’t Use Switch or If-Else in JavaScript, Instead, Try This
Braincuber Technologies
Braincuber Technologies

Posted on

Don’t Use Switch or If-Else in JavaScript, Instead, Try This

Instead of Write better switch and if…else statement in JavaScript with object

What is the switch statement?

The switch statement evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

What is the switch statement in javascript

Problems with switch

The switch case is a little difficult to read and a bit ancient, and it’s prone to debugging problems.

The odd thing about the switch case is that you have to include the keyword break at the end of each case to prevent the control from moving to the next.

in addition to that, it’s a disaster when it comes to mapping complex scenarios, which can lead to difficult debugging and nested errors.

Every time we write a switch statement, we must exercise extreme caution.

The joy of writing code is curtailed when you have to be extra cautious and that causes a huge problem.

Using objects

Let’s set up a match function to simulate switch cases

how to use objects in javascript

And you can do something like this :

how to use javascript objects instead of if else and switch statment

An object can be used as an alternative to the switch statement.

Using Object one can implement a keyed method lookup.

Summing up

This isn’t to say that the switch statement isn’t useful or that using object literals is always the best option. Object literals as switches, on the other hand, should become another tool in your javascript toolbox.

You can find the full code we implemented in this post here.
That’s it

I hope you enjoyed it!

Leave any questions, concerns, recommendations, or criticisms in the comments section. This motivates me to keep improving and writing on dev

See you later! ❤️

Read More:

7 JavaScript clean coding tips every developer should know 😎

Top JavaScript VSCode Extensions for Faster Development 🔥

Top comments (0)