Skip to main content

JavaScript: Avoiding IF ELSE statements

Often time we see a lot of IF ELSE statements in JavaScript, which will be cumbersome and hard to understand. Let's see how we can avoid IF ELSE statements to make our code much cleaner.

In this post, I'll use object literal notation to avoid using the traditional IF ELSE statements.

Let's make changes to the above code to make it a bit elegant.

As you can see I've completely eliminated IF ELSE statements in code. 

It's not just eliminating if else statements but the above snippet offer great extensibility. If you want to add another condition all you've to do is just add another function and write your code.

Trade Off:

Yes. The object literal version comes with a trade off. If you've just a single if and else blocks it is better to go with that approach instead of object literal version. The object literal version works well if you've too many conditions to check.


Popular posts from this blog

Losing precision after multiplication in SQL Server

Yesterday I was doing a little multiplication operation in SQL SERVER. The computation involves multiplication of two decimal numbers. A point to note here is that I've to be very careful while performing the calculations because it's a monetary thing. So, Whatever the calculation made, it must be very accurate such that I shouldn't miss any fractions as it costs in MILLIONS. The scenario is that I've two numbers, after multiplying each other I'm losing the precision of the values. I've tried to check my database for any faulty data that caused the issue. But the data is absolutely fine.