javascript compression tip

I was just reading through the latest article in A List Apart, and there was a little bit of discussion on the following snippet of code:

[javascript]
function getValueFor(data){

var value;

if (firstCondition(data)){
value = 1;
} else if (secondCondition(data)){
value = 2;
} else if (thirdCondition(data)){
value = 3;
} else {
value = 4;
}

return value;

}
[/javascript]

When compressed with YUI Compressor, that’s reduced to 140 bytes.

By changing it slightly, you can reduce it further:

[javascript]
function getValueFor(data){

var value = 4;

if (firstCondition(data)){
value = 1;
} else if (secondCondition(data)){
value = 2;
} else if (thirdCondition(data)){
value = 3;
}

return value;

}
[/javascript]

That’s reduced it to 133 bytes.

I think Nicholas missed a trick, though – by removing all the “else if”s and replacing them with ternary operators, he could reduce it even further:

[javascript]
function getValueFor(data){
return firstCondition(data)
?1
:secondCondition(data)
?2
:thirdCondition(data)
?3
:4;
}
[/javascript]

The above will reduce to 95 bytes. That’s 95, where the previous record was 133.

7 Replies to “javascript compression tip”

  1. heh – I wasn’t counting gzipping, which happens automatically when the server sends it. Pre-gzip, the Closure thing does 95 bytes – the same as YUI Compressor.

    Must try a few of my larger scripts in them…

Leave a Reply