Expression order in if statement

Possible duplicate:
What is the difference between (bCondition == NULL) and (NULL == bCondition)?
Shortening Javascript Comparison Instructions

I wrote my if as follows:

 if(variable1 === 1){} if(variable2 > 10){} if(variable3 == "a"){} 

But I remember reading somewhere (unfortunately, I can’t find this page anymore) that if better written as follows:

 if(1 === variable1){} if(10 < variable2){} if("a" == variable3){} 

If you put a variable on the right side of the expression.

It is right? And if so, can anyone shed some light on why this is right? Also, is this applicable to all programming languages ​​or just javascript?

TIA

+7
source share
4 answers

1 === variable1 matches the expression variable1 === 1 written in the Yoda ** notation **: the constant indicated on the left side, the variable on the right.

The main reason some programmers prefer to use this is to avoid a common mistake when writing if (a = 1) , where the programmer meant if (a == 1) or if (a === 1) . The following line of code will work, but not as expected ( a assigned a value, and the if block will always be executed):

 if (a = 1) {} 

The same expression, written in reverse order, will generate a syntax (or compilation) error:

 if (1 = a) {} 

The programmer can immediately notice the error and fix it.

I don't like or don't use Yoda notation. I try to keep my eyes open while coding.

** I cannot find out the origin of this term.

+5
source

Some people may prefer to reorder the values ​​in if second form is more protective. In fact, if you skip typing the equal sign:

 if (42 = myVar) { } 

throws a syntax error at compile time while

 if (myVar = 42) { } 

evaluates the completion value of an assignment expression, in this case 42 , which is the true value in JavaScript.

In any case, a similar error can be easily detected today using tools such as eslint ... So it makes no sense to use the first form.

+2
source

Both are correct, but the second is ugly, and I really haven't seen him. This is the same as saying

"If blue is the sky"

instead

"if the sky is blue"

. I can’t count where I read it :).

+1
source

===:

By definition, it is commutative, since it checks that both objects are the same (same type, same value).

==:

== is more complicated since there are transformations, but the specification makes it clear :

A == B is equivalent to B == A, except for the evaluation order of A and B

In other words, == is commutative.

This means that you should just use the less ugly and most familiar to readers. This is the first.

0
source

All Articles