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.

  1. Try to delete as much \n as possible and put everything in the same line, and you will possibly reduce again 🙂

  2. YUI Compressor does that automatically, so you can write properly formatted code and not worry too much about how large it is.

  3. I wonder how this fares out with the Google Closure compressor.

  4. Yeah, Closure can get it to 87 bytes gzipped. Check it out here: http://closure-compiler.appspot.com/home

  5. 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…

  6. Yea, do! It’s really very good!

  7. I love this kind of games anyway.
    Well done!
    ^_^

Leave a Reply

%d bloggers like this: