Javascript Shorthand – a quick refresher
Legacy Javascript is great. It’s readable, functional, and normally intuitive to decent developer. On the flip side, with today’s emphasis on website performance, every byte of data you include in a Javascript file or function degrades the speed at which the browser will render the content.
We can (and will, in a later post) debate the merits of differing methods of lazy-loading files, the Sizzle engine which powers jQuery, and mini-fying your code. Today I deal with a quick and easy way to squeeze the same amount of functionality into a smaller file-size – Javascript Shorthand.
While there is not an official definition of javascript shorthand defined by any of the standards-governing bodies, there are quite a few tricks that don’t trigger a ‘fail’ in the javascript validators:
1. Variable manipulation shorthand – add/multiply/subtract/divide a variable in one line
2. Ternary operators – conditional statements
3. Default variable assignments
4. Associative array shorthand
Examples:
/*
1. Add/Multiply/Divide/Subtract
Old way:
myNumber = myNumber + 7;
myNumber = myNumber - 6;
myNumber = myNumber * 8;
myNumber = myNumber / 3;
Better way:
myNumber+=7;
myNumber-=6;
myNumber*=8;
myNumber/=3
2. Ternary conditionals:
Old Way:
if (age >= 16) {
canHaveLicense = true;
} else {
canHaveLicense = false;
}
Better Way:
var canHaveLicense = (age >= 16) ? true : false;
3. Default variable assignments
Old Way:
function forestryStuff(arbLimit) {
var trees;
if(forest) {
trees = arbLimit;
} else {
trees = 100;
}
for(var i = 0; i++; i < = trees) {
//do something
}
}
Better Way: If arbLimit hasn't been passed into the function, then the value will be 100
function forestryStuff(arbLimit) {
var trees = arbLimit || 100;
for(var i = 0; i < = trees; i++) {
//do something
}
}
4. Associate Array shorthand
Old Way:
var myCar = new Array();
myCar ['Computer'] = 'Sync';
myCar ['Interior'] = 'Leather';
myCar ['Tunes'] = 'HDRadio';
myCar ['Brakes'] = 'ABS';
Better Way:
var myCar = {
'Computer' : 'Sync',
'Interior' : 'Leather',
'Tunes' : 'HDRadio',
'Brakes' : 'ABS'
};
The commas MUST be inlcuded, NO comma after the last entry. IE will fail without it.
*/