So I use the Google Closure Compiler to minify my JavaScript before using it in production. Today, I paid attention to how it minifies and optimizes(?) the code and realized this trend:

Compiling the code below :

function b(a) {
    if ( a == null ) {
       console.log('ohai');
    }
}

resulted in an optimization in the comparison expression where the literal is moved to the left and the variable to the right. As in

function b(a){null==a&&console.log("ohai")}

(Btw, it subsitutes single quotes for double quotes.) The expression remains the same if the other operand is an object. Why is moving the literal to the left of the operator an optimization of the expression?

有帮助吗?

解决方案

There's no optimisation improvement (EDIT: possibly a hasty statement, DCoder's comment for e.g. is valid), but you could make the argument that it's just prudent practice.

For example, a programmer might accidentally use a single = instead of == - resulting in assignment instead of an equality check.

The following code would silently evaluate with no error:

var a = null;
function b(a){a=null&&console.log("ohai")} // notice the single =
b(a); // nothing

However, the way google does it, it produces an error in the console (tested in Chrome):

var a = null;
function b(a){null=a&&console.log("ohai")} // notice the single =
b(a); // produces error Uncaught ReferenceError: Invalid left-hand side in assignment 

Hence, using null as the left-hand side makes these kind of user errors easier to spot.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top