I want a code-golf solution for something that does the equivalent of the following:
myFunc = function( config ){
if ( typeof config !== 'object' ) { config = {}; }
config.property = config.property || 123;
};
Basically, is there a shorter way to ensure I am always passing an object, create it if not, and assign random values to it?
I usually use a merge helper, usually
jQuery.Extend()(see documentation). But if you didn’t want to use jQuery, a similar helper would be trivial to write. But I would normally do something like:Basically, you are extending an empty object with the defaults, then the config you pass in. You will always get a new object that has at least your
defaultsproperties. I would definately recommend abstracting your object merging code into its own helper, if only so you don’t repeat the same logic in every constructor.