Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should JavaScript minifiers automatically combine var declarations?

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?

like image 606
kojiro Avatar asked Apr 24 '26 15:04

kojiro


1 Answers

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.

like image 171
user123444555621 Avatar answered Apr 26 '26 04:04

user123444555621