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, && has higher precedence than ||, so the expression is grouped as (A && B) || C even though JavaScript still evaluates left-to-right. That grouping means the final || C part gets applied more broadly than intended, causing the true result.
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 altogether and spare your teammates and your future self pain by using a proper if/else statement 🙃.