Search code examples
javascriptoptimizationuglifyjs

What does uglifyjs gain by moving expressions to the `if` condition clause?


The following code

console.log("foo");

if (window.x !== window.y) {
    const x = "x";
    console.log(x);
}

is minified using uglifyjs to

if(console.log("foo"),window.x!==window.y){const x="x";console.log(x)}

As one can see it's not longer than the more straightforward

console.log("foo");if(window.x!==window.y){const x="x";console.log(x)}

So what do they gain by moving it? Is it some tricky engine-specific optimisation or there is a reason that I cannot see?


Solution

  • Someone else pointed me to a place in their readme where they clarify it

    consecutive statements in blocks are merged into a sequence; in many cases, this leaves blocks with a single statement, so then we can remove the block brackets.

    So it is not the case here, but it saves 2 characters when you have something like

    if (<expr>) {
        console.log("foo");
    
        if (window.x !== window.y) {
            const x = "x";
            console.log(x);
        }
    }