Conditional Value Assignment and Method Invocation in JavaScript

PaperInFlames
2 min readJul 18, 2024

--

This approach will help you to write cleaner code in fewer lines. However, this won’t have much effect on performance.

Here, I’m having a flag. Based on that flag two different methods have to be called. On the other hand, based on the same flag a string value has to be assigned to another variable.

The above code can be reduced to one line as shown below.

Here, we are calling a method and returning the string value at a time with the help of a ternary operator just by separating by a comma.

In the above code, if the flag is true, then the saveUserDetails method is called and at the same time, the value active is assigned to the user status. Else, the handleInactiveUser method is called and at the same, the value blocked is assigned to the user status.

Bonus:

Here, I’ve to assign values to two different variables based on the token’s validity, at the same time I’ve to return a Boolean indicating whether the token is valid or not.

The above lengthy code can be reduced to two lines as shown below.

Hope this helps 😀🫠

--

--

No responses yet