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

In many places, I saw developers doing value == var comparisons, for example:

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

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

Is there a standard for this? And if so, what is the standard way?

+7
javascript if-statement
source share
1 answer

What you see is a yoda condition .

Yoda conditions describe the same expression, but vice versa:

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

Advantage

Placing a constant value in an expression does not change the behavior of the program (if the values ​​are not evaluated as false - see below). In programming languages ​​that use the same equal sign (=) for assignment, and not for comparison, a possible mistake is an unintentional assignment of a value instead of writing a conditional statement.

Please note that readability is clearly lacking. I personally do not prefer this.

+8
source share

All Articles