Multivariant conditions

Often, there's a need to express more complex conditions in each case, instead of just matching a singular value. If we pass true as SwitchExpression, then we are free to express custom conditional logic within each CaseExpression, as long as each CaseExpression evaluates to true when successful:

switch (true) {
case user.role === 'admin' || user.role === 'root': {
// ...
break;
}
case user.role === 'member' && user.isActive: {
// ...
break;
}
case user.role === 'member' && user.isRecentlyInactive: {
// ...
break;
}
}

This pattern allows us to express more multivariate and hybrid conditions. You may usually feel inclined toward multiple if/else/if/else statements, but if your logic can be expressed in a switch statement, then it may be best to opt for that. As always, you should consider the nature of your problem domain and its logic, and seek to make an informed decision about how you wish to implement your control flow. In some cases, a switch statement will only end up being more confusing.

In the next section, we will cover some other approaches you can use to handle complex and lengthy logic that doesn't suit native constructs such as switch.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.0.248