Code: Use JavaScript Shorthand

Chapter 8 - Ajax Optimization

You can employ a number of shorthand JavaScript statements to tighten up your code. You can use numerous abbreviated assignments to shave a few bytes.

For example, this:

x=x+1;
y=y*10;

can become this:

x++;
y*=10;

You may also find that you can reduce simple if statements using a ternary operator, so this:

var big;
if (x > 10) {
    big = true;
}
else {
    big = false;
}

can become this:

var big = (x > 10) ? true : false;

If you rely on some of the weak typing characteristics of JavaScript, this can also achieve more concise code. For example, you could reduce the preceding code fragment to this:

var big = (x > 10);

Also, instead of this:

if (likeJavaScript == true)
    { /* something */ }

you could write this:

if (likeJavaScript)
    { /* something */ }