It seems that when you declare and initialize a variable in a code block that executes conditionally, it is assumed that the variable will have this value also outside of the code block. This is wrong when the conditional code block does not get executed, in which case the variable will be undefined. As a result, further optimizations, like removing if statements, produce wrong results.
E.g., the following code produces a wrong result
function x(v) {
if (v) var w = true;
if (w) console.log("hello",v);
}
x(false);
x(true);
It produces this:
function x(a){if(a);console.log("hello",a)}x(!1),x(!0);
Which, when executed, outputs:
while it should only output the second line.
A related problem is with this code:
function x(v) {
if (v) {var w = [];for (let i=0;i<1;i++) w.push("hello");}
if (w) for (let i=0;i<w.length;i++) console.log(w[i],v);
}
x(false);
x(true);
Which produces:
function x(a){if(a){var b=[];for(let a=0;1>a;a++)b.push("hello")}for(let c=0;c<b.length;c++)console.log(b[c],a)}x(!1),x(!0);
When executed this throws an exception Cannot read property 'length' of undefined.
However, unlike the previous example, when disabling the minify-dead-code-elimination plugin, this produces correct code.
The latter example is what happens for example when processing the firebase scripts (see: https://github.com/Polymer/polymer-cli/issues/701)
It seems that when you declare and initialize a variable in a code block that executes conditionally, it is assumed that the variable will have this value also outside of the code block. This is wrong when the conditional code block does not get executed, in which case the variable will be undefined. As a result, further optimizations, like removing if statements, produce wrong results.
E.g., the following code produces a wrong result
It produces this:
Which, when executed, outputs:
while it should only output the second line.
A related problem is with this code:
Which produces:
When executed this throws an exception
Cannot read property 'length' of undefined.However, unlike the previous example, when disabling the
minify-dead-code-eliminationplugin, this produces correct code.The latter example is what happens for example when processing the firebase scripts (see: https://github.com/Polymer/polymer-cli/issues/701)