3

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?

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • It may not necessarily reduce **gzipped** size of the file, and may actually *increase* it. Without combinations, the text string ";var " will be highly compressed all over the place. In the combined text, you have an extra comma everywhere. Some minifiers combine (e.g. Google Closure and Uglify I think). – Stephen Chung Mar 20 '12 at 04:19

2 Answers2

2

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.

user123444555621
  • 148,182
  • 27
  • 114
  • 126
1

I know of one example where this would not be desirable. See this question Have I reached the limits of the size of objects JavaScript in my browser can handle?

That question was about a bug when the initialization of a variable happened in a single var statement. The question was about assigning a really gigantic literal to a variable which failed. The solution in the end was to split the object into separate var declarations.

Therefore, if compressors always did that, that would cause your code to be more likely to run into that kind of problem

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • IIRC that wasn't about a single `var`, but a single literal. –  Mar 19 '12 at 18:18
  • @pst, you don't remember correctly. My original suggestion was to split the declarations, with a single `var` , then concatting the array. The single var statement still caused the problem, the final solution was to split the array declaration into separate `var` statements, then concatting the arrays – Ruan Mendes Mar 19 '12 at 18:24