"undefined" === typeof(var)" vs "typeof(var) === "undefined"

For most, A == B is the logically the same as B == A. However, I’ve seen code written both ways. I can’t believe they are identical in terms of computation, ordering/short circuiting, etc.

Can someone please explain the technical difference between the two? Am I right in saying that reversing the order of operands is NOT 100% identical on what goes on under the hood?

They are exactly identical.

In the first, we have a string that we are comparing to the returned value of a function. That function returns a string. So, once all functions have been collapsed, we’re comparing a string to a string.

In the second, we are comparing the returned value of a function (in this case, a string) to a string. So we’re, again, comparing a string to a string.

They are completely, exactly, 100% identical. The operations performed are the same, there is no shortcut in this particular case, the comparisons are the same, the processing overhead, memory consumption and hamster wheel spins required? Exactly precisely completely the same.

Thanks - Maybe another example, what about:

obj.property === null vs null === obj.property where property does not exist?

The evaluation will short circuit earlier on the first example vs the latter?

Are you suggesting that reversing the order is merely only preference of the programmer? Viewing code written by a large company posted on GitHub they use null === varcheck vs varcheck === null. It seems there is some reason other than the fact of visual preference. I wish I had a better example.

A “Yoda Comparison” it is called when put the constant on the left you do. Back to normal english: the idiom of “Yoda Comparisons” comes from C, where this was a classic bug

if (foo = 123) { ... }

Thus assigning foo to 123 and making the test, all because of a single missing = sign. On the other hand, this Yoda comparison won’t even compile because it’s trying to assign to a constant.

if (123 = foo)

This exact sort of bug even landed in the Linux kernel once, but it was if (euid = 0), which set the effective userid to 0, which is root. Yowza.

Yoda comparisons are still used in a lot of C codebases, but they’re falling out of style pretty much everywhere else because they’re annoying to read, and any decent static analysis tool will detect assignment used as an expression anyway. The idiom comes before such tools were widely available or commonly used.

Of course what’s funny about the example in the post title is that neither side of the comparison is an lvalue, so it’d never compile as an assignment. It just looks like someone got their brain wired into Yoda comparisons and uses them in every case.


Some people just prefer to have the item that’s more likely to change, to be on the right of the comparison.

1 Like