Javascript — Enhancing the Conditions
Conditional statements allow us to control the flow of execution. In other terms, conditionals are used to make decisions(or choices) of what is executed and what is not, based on some data points.
With the advent of new javascript versions and the new functions here are some way one can do better at conditions.
Group multiple conditions with Array.includes
Times were there when we used to have multiple conditions in a single if
statement comparing different values to a single variable. Very few people made use of indexOf
to achieve the same functionality. With Array.includes
method, our conditions can now look better.
Conditional Assignment — Alternative approach to Switch
We all have encountered situations when a variable value needs to be assigned based on some condition. The Traditional way of doing this is using plain if..elseif..else
statement. Very few people made use of the switch
statement. This special scenario can be solved using Objects
in a simpler and cleaner way.
Set default values in function parameters
When we need to have some default value for named
parameters, the traditional way of using a check inside the function and assigning a default value was used. With the new feature of setting a default value in the function parameter is much elegant.
Default values for properties inside objects
When dealing with properties inside objects, we might need them to have values or set using a default one if it is not present. With help of the new destructuring
assignment, we can achieve this easily.
Don’t Nest
deep
When we need conditions to restrict the execution of certain parts of the code, we make use of if
conditions and write our logic inside them. To have a better understanding and readability always return early
.
Happy Coding ❤️❤️