Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The order of expressions in an if statement [duplicate]

Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
Javascript minification of comparison statements

Ive been writing my if statements like this:

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

But I remember reading somewhere (unfortunately I cant find that page anymore), that if statements are better off written like this:

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

Where you put the variable on the right hand side of the expression.

Is this correct? And, if so, can anyone shed any light on why this is correct? Also, does this apply to all programming languages, or just javascript?

TIA

like image 756
Jimmery Avatar asked Jan 09 '13 11:01

Jimmery


3 Answers

1 === variable1 is same as the expression variable1 === 1 written in Yoda notation**: constant listed on left hand side, variable on the right hand side.

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

if (a = 1) {}

The same expression written the other way round will generate a syntax (or compile) error:

if (1 = a) {}

The programmer can immediately spot the error and fix it.

I do not like or use the Yoda notation. I try to keep my eyes open while coding.

** I am unable to find out the origin of this term.

like image 67
Salman A Avatar answered Nov 14 '22 23:11

Salman A


Some people may prefer to reverse the order of values in the if cause the second form is more protective. In fact if you miss to type an equal sign:

if (42 = myVar) { }

throws a syntax error at compile time, while

if (myVar = 42) { } 

evaluates the completion value of the assignment expression, 42 in this case, that is a truthy value in JavaScript.

Anyway a similar error today can be easily spotted with tools such as eslint... So there's no a real point for using first form.

like image 23
Bruno Avatar answered Nov 14 '22 21:11

Bruno


Both are correct but the second one is ugly and I haven't really seen much of it. It's the same as say

"If blue is sky"

instead of

"if sky is blue"

. Can't recal where I have read it :).

like image 27
lukas.pukenis Avatar answered Nov 14 '22 22:11

lukas.pukenis