Posts: 3,985
Name: Abel Mohler
Location: Asheville, North Carolina USA
|
Here is a more elegant solution.
The reason this works is that the logical OR of JavaScript returns values in left to right precedence when assigning values. You can simply do something like this (I'm using a more extreme example where the input is a whole object with several properties):
Code:
function myFunction(obj) {
var defaults = {
prop1: "hello",
prop2: "world",
prop3: "goodbye",
prop4: "world"
}
//the magic
obj = obj || defaults;
//logic goes here...
}
Of course, this will work with any value, not just a set of objects. Set a default then say {variable = variable || default} where variable is the function input.
Last edited by wayfarer07; 01-28-2009 at 12:32 PM..
|