21 Jul

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:

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;

}

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

By changing it slightly, you can reduce it further:

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;

}

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:

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

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

7 thoughts on “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 to Stef Cancel reply

%d bloggers like this: