Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Constant first in an if condition [duplicate]

Tags:

javascript

I often see if structures being coded like this:

if (true == a)
if (false == a)

Why do they put the constant value first and not the variable? as in this example:

if (a == true)
if (b == true)
like image 752
Xavier Geerinck Avatar asked Jul 10 '13 12:07

Xavier Geerinck


1 Answers

This is called yoda syntax or yoda conditions.

It is used to help prevent accidental assignments.

If you forget an equals sign it will fail

if(false = $a) fails to compile

if($a = true) assigns the value of true to the variable $a and evaluates as true

The Wordpress Coding Standards mention this specifically:

if ( true == $the_force ) {
    $victorious = you_will( $be );
}

When doing logical comparisons, always put the variable on the right side, constants or literals on the left.

In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.

A little bizarre, it is, to read. Get used to it, you will.

like image 126
user20232359723568423357842364 Avatar answered Nov 02 '22 07:11

user20232359723568423357842364