5

Is there a specific reason why I have seen many people writing

if(1 === a) {...}

instead of

if(a === 1) {...}

I had given an answer in which I wrote something like Array === obj.constructor which is when someone asked me that he has often seen people writing like this instead of obj.constructor === Array.

So does it really matter which way I use?

shinobi
  • 2,511
  • 1
  • 19
  • 27
  • could be since in `x===y` x is evaluated first and if x is NaN false is returned ASAP as per spec http://www.ecma-international.org/ecma-262/6.0/#sec-strict-equality-comparison – gurvinder372 Jun 26 '16 at 06:45
  • It's a placebo practice: people believe it will solve their most important development problem. – zerkms Jun 26 '16 at 08:46

1 Answers1

8

It's yoda conditions:

Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:

if ("red" === color) {
    // ...
}

This is called a Yoda condition because it reads as, “red is the color”, similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands:

if (color === "red") {
    // ...
}

This typically reads, “color is red”, which is arguably a more natural way to describe the comparison.

Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available.

Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions.

Anthony Astige
  • 1,919
  • 1
  • 13
  • 18