Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Boolean operators don't distribute
// I see this mistake often (and have made it myself before)
// What's the bug with this function?
function isFavSeason(season) {
return season === 'spring' || 'summer' ? 'yes' : 'no'
}
// Let's try it and find out
console.log(isFavSeason('spring')) // yes
console.log(isFavSeason('summer')) // yes
console.log(isFavSeason('fall')) // yes
console.log(isFavSeason('winter')) // yes
// What? That's not what we were hoping for!
// The problem is our human brains are really good at what's known in
// math as the distributive property. We read that conditonal as:
// "season equals spring OR season equals summer", but what the JavaScript engine sees
// is "If season equals spring OR summer" and the string 'summer' is ALWAYS true,
// because a non-empty string is truthy. That's why this always returns `yes`.
//
// Boolean logic does not distribute, that is the `season ===` doesn't get applied
// to both 'spring' and 'summer', but only to 'spring'. We need to do the explicit
// work of distributing the comparisons ourselves.
function isFavSeason(season) {
return season === 'spring' || season === 'summer' ? 'yes' : 'no'
}
// That will work as expected. Granted, we could make this better, and in
// such a way we don't have to make all the comparisons.
function isFavSeason(season) {
const favSeasons = ['spring', 'summer']
return favSeasons.includes(season) ? 'yes' : 'no'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment