Javascript shorthand @ d’bug
The d’bug blog has a nice little post on javascript shorthand that’s worth looking at if you don’t know these tricks. Stuff like declaring variable defaults with the logical OR or using ternary , etc. One thing to be careful of is type coercion. Basically if you say “if (x) …” you can get a false evaluation if x is an empty string, null, zero, or false. Check out the mootools functions $chk, $pick, and $defined for easy ways to avoid these kinds of things. You can also express conditionals using === and !== to ensure you are evaluating for the right condition.
/*
-----------------------------------------------
Conditional Shorthand 1
-----------------------------------------------
If "a" is not defined, or is not equal to true,
then "a" is equal to "b".
Longhand:
var a, b;
if ( !a ) {
a = b;
}
Shorthand:
*/
var a, b;
a = a || b;
/*
-----------------------------------------------
Conditional Shorthand 2
-----------------------------------------------
If some condition is equal to true,
then "a" is equal to "b", or else
"a" is equal to "c".
Longhand:
var a, b, c;
if ( true ) {
a = b;
} else {
a = c;
}
Shorthand:
*/
var a, b, c;
a = ( true ) ? b : c;
