Skip to content Skip to sidebar Skip to footer

Why Using ('function' === Typeof X) And Not (typeof X === 'function')

In some open source JavaScript projects, I saw people checking if a variable is a function or not with ('function' === typeof x). I wonder why people use that instead of (typeof x

Solution 1:

These are called "Yoda Conditions" (because they sound like Yoda):

yoda

Some people prefer them, because an Invalid left-hand side in assignment error will be thrown if = is used by mistake instead of == or ===. In the most usual order (i.e., if(count = 5), a silent assignment will happen, and will screw up the program logic.

Note that 'function' === typeof x is not a good example; since typeof x will evaluate to a string, a misplaced assignment operator will always throw an error in this case, regardless of the order of the operands.

Solution 2:

They are identical expressions. When you compare with == or ===, it doesn't matter what is on which side of the expression.

if(null === myVar)

if('hello' === str)

etc. are all valid.

If one of two expressions is quite long, you may want to put it on the right hand side so it's easier for the eye to see what is being compared.

Solution 3:

There is no probably no reason but it might historically come from the = and == difference, where it does matter. See the thing with

if (a = 5)

and

if (5 = a)

is that the first one doesn't check if a is 5, it assigns 5 to a. So people came up with the reverse check, which throws compile errors, since you cannot assign to 5, etc. This way you can fix your code if you forgot one =. So it might be for consistency purposes as well.

Solution 4:

They are identical. Some Java programmers tend to write it this way as an usual best practice in Java to write null != object.getSomething() instead of object.getSomeThing() != null. This is for avoiding the possible NullPointer

But, in Javascript this makes no sense. And as you pointed, (typeof x === 'function') is the natural way.

Post a Comment for "Why Using ('function' === Typeof X) And Not (typeof X === 'function')"