I just discovered that YUICompressor (2.4.7) does not combine var declarations. For example,
var x = 1;
var y = 2;
compresses to
var a=1;var b=2;
I assume it would be reasonable to expect a minifier to be able to combine consecutive var declarations, like so:
var a=1,b=2;
But my real question is is it reasonable to expect/possible (for a minifier) to automatically and safely combine non-consecutive var declarations in a single function?
It depends. If you're talking about declarations with initialization then: No.
Consider this:
(function () {
var x = 1;
console.log(y); // undefined
var y = 2;
})();
(function () {
var x = 1, y = 2;
console.log(y); // 2
})();
However, the following is safe and should be done by minifiers:
(function () {
var x = 1, y;
console.log(y); // undefined
y = 2;
})();
It is certainly possible; the compressor scans the whole function for contained var statements prior to generating output. This is necessary to compress variable names.
Note that there is one possible tricky variant, which consists in extending the parameter list, and thus saving extra bytes by completely eliminating any var statements:
(function (x,y) {
x = 1;
console.log(y); // undefined
y = 2;
})();
However, this changes the function's (rarely used) length property and thus is not to be expected from minifiers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With