简体   繁体   中英

JavaScript Uglify is different and correct?

I have a uglified JS file where I want to get the beautified version and then uglify it with grunt again. And I expect it to be the same as the first uglified file.

But when I do it one part, with the 'if', is different.

This is a part of the uglified file:

...function sendRequest(requestParams){if(Object.keys(requestParams).length>=1){$.ajax({type:"POST",url:VideoSearchUrl,data:requestParams,dataType:"xml"}).done(function(xmlDoc){buildResult($(xmlDoc)),responses++,requests==responses&&postSearchActions()})}}function...

But the uglified version from the beautified file look like this:

...function sendRequest(requestParams){Object.keys(requestParams).length>=1&&$.ajax({type:"POST",url:VideoSearchUrl,data:requestParams,dataType:"xml"}).done(function(xmlDoc){buildResult($(xmlDoc)),responses++,requests==responses&&postSearchActions()})}function...

Why is the 'if' dropped? In an online uglifier it is still there.

Or does it mean the same?

This is correct due to Short Circuit Evaluation .

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is short-circuit evaluated to false.
  • true || (anything) is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated , so any side effects of doing so do not take effect. Also, note that the anything part of the above expression is any single logical expression (as indicated by the parentheses).

(Emphasis by me)

 a = 1; b = 1; if (a == b) { console.log(1); } // will log because it's like // (true) && expression a == b && console.log(2); // will NOT log because it's like // (false) && expression a != b && console.log(3); 

Why bother?

true&&expression is shorter than
if(true){expression} (every byte counts)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM