Code: Remove Whitespace Carefully

Chapter 8 - Ajax Optimization

JavaScript is fairly whitespace-agnostic and you can easily reduce the whitespace between operators. For example, instead of writing this:

var str = "JavaScript is " +
    x +
    " times more fun than HTML ";

you can write this:

var str="JavaScript is "+x+" times more fun than HTML";

Be cautious when condensing, however. JavaScript treats line breaks as implicit semicolons. If you do not terminate lines with semicolons, you may find that whitespace reduction can cause problems. For example, the following legal JavaScript uses implied semicolons:

x=x+1
y=y+1

A simple whitespace remover tool might produce this:

x=x+1y=y+1

This code would obviously throw an error. If you add in the needed semicolons, the code will work:

x=x+1;y=y+1;