Javascript — Enhancing the Conditions

Marudhu Pandiyan G
3 min readSep 22, 2018

--

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.

Grouping Conditions with Array.includes

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.

Conditional assignment

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.

Use `default` values in function parameters

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.

Default values for properties

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.

Return early from functions

Happy Coding ❤️❤️

--

--

Marudhu Pandiyan G

Polyglot | Freelancer | Javascript ❤ | ReactJs | Nodejs | Helps new entrepreneurs & other freelancers, building awesome Web apps. http://marudhupandiyang.in/