function shouldAlert(durationInWarehouse, temperature) {
const CRITICAL_TEMPERATURE = 30; // °C
const SECONDARY_TEMPERATURE = 25; // °C
const CRITICAL_DURATION = 7; // Days
return temperature > CRITICAL_TEMPERATURE
&& durationInWarehouse > CRITICAL_DURATION
|| temperature > SECONDARY_TEMPERATURE;
}
console.log(shouldAlert(5, 26)); // true (should be false) console.log(shouldAlert(8, 26)); // true console.log(shouldAlert(8, 32)); // true
In JavaScript, the && operator has higher precedence than the || operator. This means that in a statement with both these operators, the parts with &&`` will be evaluated first. To fix the issue, we need to add parentheses around the ||` part of the statement.
function shouldAlert(durationInWarehouse, temperature) {
const CRITICAL_TEMPERATURE = 30; // °C
const SECONDARY_TEMPERATURE = 25; // °C
const CRITICAL_DURATION = 7; // Days
return temperature > CRITICAL_TEMPERATURE
|| (
durationInWarehouse > CRITICAL_DURATION
&& temperature > SECONDARY_TEMPERATURE
);
}
Or you can just avoid ternaries all together and spare your teammates and your future self pain by using a proper if/else statement 🙃.