I've used JavaScript for a while and thought it would be useful (especially for those new to the language) to list some of my favorite shortcuts.
Ternary operator
Replace: if(a) then {b} else {c}
With: (a) ? b:c;
Unary plus operator
Replace parseInt(x,10) + parseInt(y,10)
with +x + +y
Array creation
Replace var ary = new Array();
with var ary = [];
Declaring variables
Replace var x; var y; var z = 3;
with var x, y, z=3;
Multiline string (almost here-doc style)
Replace:
var str = 'this';
var str += 'covers';
var str += 'multiple';
var str += 'lines';
with:
var str = 'this \
covers \
multiple \
lines";
What others do you use?
To shorten the if condition blocks.
From:
var x;
if (a) {
x = a;
} else if (b) {
x = b;
} else {
x = 100;
}
to:
x = a || b || 100;
You can use && to do the similar logic as well.
Convert to string by adding empty string. Example:
var n = 1;
var s = 1 + '';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With