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.
Comments
Post a Comment