How to optimise JS code for minimisation purposes

What it is about

  • Writing a code which can be efficiently minimised
  • Discovering tricks to write short code
  • Use language flexibility to achieve the previous points

What it is not about

  • Optimisation on the code's performances


  • Smaller code == less bandwidth == faster app
  • Some advanced techniques good to know for any developer
  • Because it's fun

Kind of changes

  • The good
  • The bad
  • The ugly

The good changes

  • Code readability not really reduced
  • Will save bytes during the code minimisation

var keyword factorisation

  • If var not factorised, YUI Compressor will fail
  • Cafeful with commas vs semi column

var keyword factorisation

Duplicated strings

  • Strings are not minimisable
  • Sometimes useful to factorise them


Duplicated strings

Depends on the the string's length and the number of times it's repeated.

Duplicated string - case 1

Duplicated strings - case 2

Arrays vs Objects

  • Objects' attributes are not minimised
  • Attributes can be used as array's elements
  • array's elements are strings

Arrays vs Objects

Arrays vs Objects

  • Depends also on the size of the used attributes and of the number of times they are used

Know your operators

  • classic operations (+, -, /, *)
  • bitwise operations (|, &, ^, ~)
  • To work with integers (as results)

~ operator

  • Bit definition: one-complement, switch every 1-bits to 0 and 0-bits to 1
  • Integer definition: For signed integers, ~a = -1*a - 1
  • Interesting case: ~-1 = 0

~ operator

Floor operation

The bad changes

  • Will not help to minimise
  • Will reduce the code's readability


Comments are just removed in a minimised code, don't feel bad about commenting your code


All useless spaces will be removed from the code, let your code breathe.

Variables names

Variables are automatically renamed, so use meaningful names.

The ugly changes

  • Useful changes to minimise the code
  • Highly reduce the code readability
  • To use only if the code must be as small as possible, at any price


Only in JavaScript?

Some of those tricks are useful in other languages, but mostly for fun or challenging purposes.


  • Duplicated code can often be optimised
  • Optimise only when your code is ready
  • Have fun playing arround with the languages

How to optimise JS code for minimisation purposes

By Ghislain Rodrigues

How to optimise JS code for minimisation purposes

  • 681