Q:

Javascript default array/object parameter value

I'm making up a way of setting function array parameter to a default value (one ES5 not new ES6/2015).
My first idea was this:
window.fnc = function(args){
    defaults = {
        height: 120,
        width: 32
    }

    args = args || defaults;

    console.log(args['height']+'x'+args['width'])

}

and will be used like this:
fnc({height:45, width:12}); //Result: 45x12

or
fnc(); //Result: 120x32

This works ok. But of course at line #7 the args is replaced by defaults or it is not, so if either one of the 2 values are missing i get an undefined.
fnc({height:45}); //Result: 45xundefined

How do I go about this?

A:

I use this code snippet from time to time:
 args = args || defaults;
     for (var opt in defaults) {
        if (defaults.hasOwnProperty(opt) && !args.hasOwnProperty(opt)) {
            args[opt] = defaults[opt];
        }
    }

Basically you iterate over all the values from the default arguments (for (var opt...) and check against the values of the arguments whether it is missing or not. (if (defaults.has...). If it is missing, add the default value (args[opt] =...).
(I think I even found this snippet on SA, but not sure. Will add a link to the original answer if so.)

