The order of expressions in an if statement

1 === variable1 is same as the expression variable1 === 1 written in Yoda notation**: constant listed on left hand side, variable on the right hand side.

The main reason why some programmers choose to use it is to avoid the common mistake of writing if (a = 1) where the programmer actually meant if (a == 1) or if (a === 1). The following line of code will work but not as expected (a is assigned a value and if block will always get executed):

if (a = 1) {}

The same expression written the other way round will generate a syntax (or compile) error:

if (1 = a) {}

The programmer can immediately spot the error and fix it.

I do not like or use the Yoda notation. I try to keep my eyes open while coding.

** I am unable to find out the origin of this term.


Some people may prefer to reverse the order of values in the if cause the second form is more protective. In fact if you miss to type an equal sign:

if (42 = myVar) { }

throws a syntax error at compile time, while

if (myVar = 42) { } 

evaluates the completion value of the assignment expression, 42 in this case, that is a truthy value in JavaScript.

Anyway a similar error today can be easily spotted with tools such as eslint... So there's no a real point for using first form.