There is a piece of JavaScript syntax I, and others, seem to always want to work and it doesn't.
const isThisOrThat = 'that' === ('this' || 'that')// this is false
Why doesn't this work? Let's talk about it!
Inside the parens
If we go by order of operations, the inside expression evaluates first.
What does "this" || "that"
mean in JavaScript?
I'll be honest, this one breaks my math brain a bit. In math, a || b = b || a
. The or operator is commutative, so order doesn't matter. That's not true in JavaScript, order matters a lot.
Let's look at two examples.
const example = '' || 'that'// "that"
The first thing JavaScript does is check for the "existence" of the first value. JavaScript is checking for a falsey value, empty string is falsey. Since the first value doesn't exist, it returns the second value.
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 "this"
.
Equality check
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.
Making sure this works
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
Or is weird
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.