Grouping multiple logic statements
suggest changeYou can group Boolean expressions with parentheses to build a more complex condition. That is especially useful in if statements. && binds more tightly than ||, so the parentheses in the next condition do not change the result. They still make the intended grouping obvious.
if ((age >= 18 && height >= 5.11) || (status === 'royalty' && hasInvitation)) {
console.log('You can enter our club');
}
We could also move the grouped logic to variables to make the statement a bit shorter and descriptive:
const isLegal = age >= 18;
const tall = height >= 5.11;
const suitable = isLegal && tall;
const isRoyalty = status === 'royalty';
const specialCase = isRoyalty && hasInvitation;
const canEnterOurBar = suitable || specialCase;
if (canEnterOurBar) console.log('You can enter our club');
Removing the parentheses from this particular condition produces the same result. Parentheses still make the intent easier to read and can prevent mistakes when the operators are less familiar.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents