Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"value == var" versus "var == value"

At many places, I've seen developers doing value == var comparisons, like this:

if ('https' === location.protocol) {
   port = 8443;
   protocol = 'wss://';
   isSecure = true;
}

I know that a == b is same as b == a, so why do people use value == var instead of var == value?

Is there a standard for this? And if yes, which is the standard way?

like image 714
Ashutosh Jha Avatar asked Mar 29 '17 08:03

Ashutosh Jha


1 Answers

What you are seeing is yoda condition.

Yoda conditions describe the same expression, but reversed:

if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."

The advantage is

Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.

Note that it is clearly lack of readability. I personally don't prefer this way.

like image 111
Suresh Atta Avatar answered Oct 08 '22 00:10

Suresh Atta