Friday, January 14, 2011

Shortest conditional statement

/*
Short hand conditional

This is similar to Optional constructor arguments
utilising right hand evaluation if left hand results 
in boolean true
*/

var foo = 2, bar;
foo == 2 && (bar = 3);


/*
Can also be used to call functions conditonally
*/
foo == 2 && baz();
Thursday, January 13, 2011

Object properties to Array

/*
Collecting object properties into
an Array
*/

var i = 0, arr = [];
var foo = {bar: "value bar", baz: "value baz"};

for(arr[i++] in foo)


/* 
Result:
arr == ["bar", "baz"] 
*/
Monday, January 10, 2011

Optional constructor arguments

/*
Setting object parameters 
optionally in the constructor

bar is required, baz is optional


Note:
false or 0 will result in no value being 
used. Better to use conditions in this case.
*/

function foo(bar, baz) {
    this.bar = bar;
    baz && (this.baz = baz);
}

foo.prototype = {
    bar: "",
    baz: ""
};

Function arguments with defaults

/*
Function with defaulted arguments
bar is required, baz is optional with a default


Note:
false or 0 will result in the default value being 
used. Better to use conditions in this case.
*/
function foo(bar, baz) {
    baz = baz || 'default value';
}