Mastering UglifyJS: Advanced While, Conditional, Block, and IF Optimizations
This article continues the deep dive into UglifyJS compression, presenting advanced techniques for optimizing while loops, ternary conditional expressions, statement blocks, and IF branches, including rules for removing dead code, merging statements, and transforming structures to achieve maximal size reduction in JavaScript output.
4. While Loop Compression
Rule 4.1 : Remove while loops that will never execute and convert while(true) to for(;;) to save characters.
// while(false) is removed
for(;;){ // while(true) converted, saves 4 characters
C();
D();
}5. Conditional Expression Compression
Rule 5.1 : If a condition is preceded by a logical NOT, drop the NOT and swap the true/false branches. cond ? no() : yes(); Rule 5.2 : When the condition is a constant boolean, replace the whole expression with the selected branch.
yes();
no();6. Statement Block Compression
Rule 6.1 : Consecutive expression statements can be merged into a single comma expression.
function A(){
B(), C(), d = 1;
}Rule 6.2 : Multiple var declarations can be combined into one.
function A(){
var a, b, c;
}Rule 6.3 : Statements after return, throw, break or continue that are unreachable can be removed (except declarations that are hoisted).
function A(){
function B(){ }
return false;
var a = 1;
}Rule 6.4 : Merge the final return with preceding expression statements.
function A(){
return B(), C(), D();
}7. IF Branch Optimization
Rule 7.1 : Remove IF/ELSE branches whose condition can be evaluated at compile time.
A();
D();Rule 7.2 : Eliminate empty IF/ELSE branches by negating the condition.
if (A){
B();
}
if (!C){
D();
}Rule 7.3 : Reverse IF/ELSE when the negated condition yields shorter code.
if (c){
B();
} else {
A();
}Rule 7.4 : Combine nested IFs with an empty ELSE into a single logical AND.
if (A && B){
C();
}Rule 7.5 : When the IF block ends with a control‑flow statement, move the ELSE code after the IF.
if (A){
B();
return;
}
C();Rule 7.6 : Merge two single‑statement returns into a conditional expression. return A ? B() : C(); Rule 7.7 : Convert single‑statement IF/ELSE into a ternary expression, then apply the conditional‑expression rules.
Rule 7.8 : When one branch is empty and the other contains a single statement, replace the IF/ELSE with logical AND (&&) or OR (||) expressions.
A && B();
C || D();For a complete source‑code analysis, refer to the original article linked in the text.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
