Javascript ||, aka Why Doesn't This Work?!

Laurie - Sep 29 '20 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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 = "" || ""
// ""
Enter fullscreen mode Exit fullscreen mode

So what happens if the first value is truthy, as in our original example?

const example = "this" || "that"
// "this"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Alternatively, we can use an array check. This one feels a bit more natural.

const isThisOrThat = ["that", "this"].includes("that")
// true
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player