3

A few time ago, I saw in a JavaScript application (I don't remember which one is) the use of true === $var instead of $var === true. Example:

if (true === $var) {
    // do something
}

I think these comparisons are differnet but I can see why — someone can explain it for me? And plus: when I should use and when I shouldn't.

Duplicated?

I searched on the web but no results.

Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96

3 Answers3

7

There is no difference between them.

Yoda comparisons are done by some people to prevent a typo (missing =s) creating an assignment instead of a comparison (since true = $var will throw an error while $var = true will not).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

I think this is just a best practice kind of thing, at least I'm used to seeing the suggestion when coding in languages such as C#, where it's easy to accidentally do

if(someVar = 1)

instead of:

if(someVar == 1)

Doing it in reverse prevents that possibility, as the compiler will pick up the fact that you can't assign the value of a variable to a literal (or constant, if you use constants).

Nat Wallbank
  • 1,377
  • 12
  • 12
0

No there is not any difference in both

But there is difference in $var == false and $var === false

$var = 0;
$var == false // TRUE
$var === false // FALSE

=== will also compare the variable type. It checks if it's a bool, string or integer for example.

$var = "1";

$var == 1 // TRUE
$var === 1 // FALSE 
  • 2
    Why the downvotes? Whilst the answer does not describe the Yoda comparison pattern in the other answers, it is factually correct in stating that comparatively the operations are equivalent - as stated by the most voted answer. The OP probably knows about the difference in equality checking between == and === as the latter is used in the question, but this is also useful information for beginners. I can understand not upvoting, but a downvote seems a bit harsh. – pwdst Dec 12 '13 at 13:08
  • @pwdst The information is useful and I'm neutral (I don't downvoted the question), but if you think a little better, there's something wrong on its essence: the question is not about the operators and that's why I think that our buddy Avneesh received some downvotes. – Guilherme Oderdenge Jan 09 '14 at 13:55
  • @GuilhermeOderdenge The first line of the answer does address the question - the additional information is just that, additional. Whilst the answer could certainly do with being expanded upon, it is not wrong. – pwdst Jan 09 '14 at 14:32
  • Hmmm, you're right. I read again and you win, hehe. Thanks! – Guilherme Oderdenge Jan 09 '14 at 15:26