Combining conditions in JavaScript
Although the operation &&
takes precedence
over ||
, it is often more convenient to use
grouping parentheses to explicitly indicate the
precedence of operations:
let num = 3;
if ( (num > 0 && num < 5) || (num > 10 && num < 20) ) {
console.log('+++');
} else {
console.log('---');
}
Of course, grouping can also be used when you need your own priority of operations, and not the one that is obtained by default:
let num1 = 3;
let num2 = 5;
if ( num1 > 0 && (num2 == 3 || num2 == 5) ) {
console.log('+++');
} else {
console.log('---');
}
In the code below, specify the precedence of operations explicitly:
let num = 3;
if (num > 5 && num < 10 || num == 20) {
console.log('+++');
} else {
console.log('---');
}
In the code below, specify the precedence of operations explicitly:
let num = 3;
if (num > 5 || num > 0 && num < 3) {
console.log('+++');
} else {
console.log('---');
}
In the code below, specify the precedence of operations explicitly:
let num = 3;
if (num == 9 || num > 10 && num < 20 || num > 20 && num < 30) {
console.log('+++');
} else {
console.log('---');
}