Javascript minification of comparison statements

前端 未结 2 1264
天涯浪人
天涯浪人 2020-12-20 22:27

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          


        
2条回答
  •  不知归路
    2020-12-20 23:07

    [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.

提交回复
热议问题