Domanda

I saw a couple of times code like "expected" === variable instead of variable === "expected".

Why is that? Is it performance or readability related? I personally find it more confusing and I always wondered why would someone write the string first, and then the variable in a comparison operation.

È stato utile?

Soluzione

The main reason is to protect against a single equals typo causing assignment. Commonly known as Yoda Conditions (thanks Paul S in the comments).

E.g:

var i = 1;
if(i = 2)  //no error, but unexpected behavior 
if(2 = i) //error - invalid left hand side assignment. 

The if(i=2) option would cause unexpected behaviour because it would assign 2 to i and also enter the if statement which could be a subtle bug that is hard to track down compared with receiving an error. This approach is even more useful for a compiled language such as C++ where the compiler will raise an error so you know about it during compile time. C# and Java compilers don't allow conditionals to be an assignment, so the ordering is of less value there.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top