1. Boolean Shorthand Replacement
// Normal true, false // Shorthand !0, !1 // Because true === !0, false === !1
2. Convert to Number
var a = "1"; // Normal new Number( a ); // Shorthand +a; // Result 1
3. Convert to fixed Number
var a = 3.5; // Normal : parseInt( a, 10 ); // Shorthand ~~a; // Result 3
4. Clever way to boolean check if something bigger than -1
var array = [ "a", "b", "c", "d" ];
// Normal
if ( array.indexOf('a') > -1 )
// Alternative
if ( !!~array.indexOf('a') )
// Result true
5. Chain operations with comma
// Normal
function a() {
if ( true ) {
window.location.hash = 'page1';
return true;
} else {
return false
}
}
// Shorthand
function a() {
return ( true ? ( window.location.hash = 'page1', !0 ) : !1 );
}
// Result true
6. Using [object Array].length to increment its array
var array = new Array();
// Normal
for ( var i=0; i<6; i++) {
array[i] = i;
}
// Alternative
for ( var i=0; i<6; i++) {
array[array.length] = i;
}
// Result [1,2,3,4,5,6]
7. Alternative for switch-case
var something = 1;
// Normal
switch( something ) {
case: 1
return "a";
case: 2
return "b";
case: 3
return "c";
default:
return "d";
}
// Alternative
var case = {
1: "a",
2: "b",
3: "c",
def: "d"
}
return case[ something ] || case.def;
8. Short function calling
var a = 1;
function b() { return "b"; }
function c() { return "c"; }
// Normal
if ( a === 1 ) {
b();
} else {
c();
}
// Shorthand
( a === 1 ? b : c )();
Any others?