const isThisOrThat = 'that' === ('this' || 'that')// this is false
Why doesn't this work? Let's talk about it!
If we go by order of operations, the inside expression evaluates first.
I'll be honest, this one breaks my math brain a bit. In math,
Let's look at two examples.
const example = '' || 'that'// "that"
This happens even if the second value is also falsey.
const example = '' || ''// ""
So what happens if the first value is truthy, as in our original example?
const example = 'this' || 'that'// "this"
example evaluates to
Now we start to realize why our expression up top doesn't work. We can break it into two pieces.
const example = 'this' || 'that'const isThisOrThat = 'that' === example// false
At the time that we're checking equality, the string
"that" is nowhere to be found.
What makes this strange is that order matters.
const example = 'that' || 'this'const isThisOrThat = 'that' === example// true
Flipping the original or expression changes the resulting equality check.
If we truly want to check both strings, we need to check equality twice.
const isThisOrThat = 'that' === 'this' || 'that' === 'that'// true
Alternatively, we can use an array check. This one feels a bit more natural.
const isThisOrThat = ['that', 'this'].includes('that')// true
People use or a lot to flip values or set defaults, etc. It's never been my favorite because of examples like the ones above. Once you start composing that expression it can confuse the issue.