What is the benefit of the former over the later? What do you prefer?
The goal is to prevent an assignment if you enter a single '=' by mistake.
var a = 2;
if (a = 1) alert('Oops');
Witing:
if (1 = a)
will result in:
Invalid left-hand side in assignment
You can achieve this with a good linter, and skip the unnatural looking expression.
Back in my Java days, I learned to avoid NullPointerExceptions in conditions which should detect Null.
I did a lot like this:
if (myVariable.itsNull == Null) { ... }
In case of myVariable is Null Java throws an unwanted NullPointerException, even though I wanted to detect Null, but on a different position. The trick was to switch the conditions
if (Null == myVariable.itsNull) { ... }
Now myVariable can be Null without causing NPE's.
Then I entered the world of Ruby. By learning Ruby and CoffeeScript, it was the same, checking the const against the variable.
Now in JavaScript I stick to it, still doing if (1 == myVariable) { ... }.
I didn't know about the wanted '==' typed '=' mistake. You can find the left-constant comparison useful in coffee-script too! Although in different scenario as in coffee-script the compare operation is done with the is keyword.
In JS I would write
indexOf(item) === 1;
naively in CS I might try
indexOf item is 1
but the compiled JS is
indexOf(item === 1); // oops
so the correct code is:
indexOf(item) is 1
and finally, to avoid the parentheses I settled with the pattern
1 is indexOf item
which produces
1 === indexOf(item);
Nice to know that it's called Yoda conditions.
Anthony Lapenna
Open-source enthusiast
It's called Yoda conditions, see https://en.wikipedia.org/wiki/Yoda_conditions for more information !
Personally, I prefer to use the typical order.