This comes up every few months on my various teams, so I decided to compile a nice, simple list of them for easy reference.
Advantages to shorthand:
- Easier to read
- Saves time
- Saves bytes
Variable Increment/Decrement
Very useful for loops.
growCount = growCount + 1;
//Can be rewritten as:
growCount++;
shrinkCount = shrinkCount - 1;
//Can be rewritten as:
shrinkCount--;
Variable Change
moreStuff = moreStuff + 100;
//Can be rewritten as:
moreStuff += 100;
lessStuff = lessStuff - 100;
//Can be rewritten as:
lessStuff -= 100;
wayMoreStuff = moreStuff * 100;
//Can be rewritten as:
wayMoreStuff *= 100;
wayLessStuff = wayLessStuff / 100;
//Can be rewritten as:
wayLessStuff /= 100;
Ternary Operator
This is a great code saver for when you have a variable dependent on a if-else statement.
if(myAge > 16) {
canDrive = true;
} else {
canDrive = false;
}
//Not only does this lend itself to scoping problems,
//there's a faster way to do this:
var canDrive = (myAge > 16) ? true : false;
We just reduced five lines of code to one.
Ditching the Brackets
You can ditch the brackets around blocks of code, if you only have one statement.
//For loops:
for (i=0; i < max; i++) console.log(i);
//If statements
if (doorUnlocked) goIn = true;
Default Values in JavaScript Functions
Until we get JavaScript 2.0, we have to do some fancy footwork to make JavaScript act like "grown up" programming languages.
//The old stand-by.
function cheer(cheerFor) {
if(cheerFor === null || cheerFor === undefined || cheerFor === ''){
cheerFor= 'team';
}
alert('Go ' + cheerFor + '!');
}
cheer('Fighting Studebakers'); //With argument
cheer(); //Without argument
//Can be written shorter:
function cheer(cheerFor) {
cheerFor = cheerFor || 'team';
alert('Go ' + cheerFor + '!');
}
cheer('Fighting Studebakers'); //With argument
cheer(); //Without argument