Skip to content Skip to sidebar Skip to footer

Javascript Minification Of Comparison Statements

I was looking over one of the minified js files generated by closure. I found that wherever I'm checking for equality between a variable and string like, a == '13' || a == '40' cl

Solution 1:

This is done as for a minor gzip compression advantage. If you have "x == 1" and "1 == x" the compiler switches it to "1 == x" in both cases and you get more regular code that compresses better. The win is so minor, that I've considered deleting the code and saving the cpu cycles, but it is on for now. It has nothing to do with preventing programmer errors as it will never switch "x = 2" into "2 = x" as that would change the meaning of the program.


Solution 2:

[UPDATE: See @John's answer, it makes more sense as to why a js minifier would do this, and should be the accepted answer]

As a general concept, this is to avoid programmer error. If you were modifying the code manually and put the variable first and constant second, it's possible to accidentally type:

a == '40' || a = '13'

Oops! We just set a to '13' instead of comparing. By putting the constant on the left, we avoid this possibility:

'40' == a || '13' = a

Will throw an exception because you can't put a constant string on the left hand of an assignment operation.

So in some schools of thought, it's best practice to always put the constant on the left when doing equality comparison against a constant. Looks like closure follows that practice.

These are called "yoda conditions".

Note that my personal preference is to actually to just put the constant on the right in most cases, because the code tends to read better, so I don't think the tradeoff is good enough. But I see the logic behind yoda conditions.


Post a Comment for "Javascript Minification Of Comparison Statements"