Value assignment & method calling based on a flag at the same time in JS.
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.
isActiveUser ? saveUserDetails() : handleInactiveUser();
userStatus = isActiveUser ? 'active' : 'blocked';
The above code can be reduced to one line as shown below.
userStatus = isActiveUser ? (saveUserDetails(), 'active') : (handleInactiveUser(), 'blocked')
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.
Hope this helps 😀🫠