1

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?

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

You can iterate the keys of default to copy the one missing in args.

window.fnc = function(args){
    defaults = {
        height: 120,
        width: 32
    }

    //args = args || defaults;
    if(args == null)
      args = defaults;
    else {
      for(var i in defaults) {
        if(args[i] == null) args[i] = defaults[i];
      }
    }

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

}

If you have sub-objects in defaults, you will need to do a recursive function.

EDIT:

Recursive example:

// check if obj is an object
function isObject(obj) {
  return typeof obj == "object";
}
// check if obj is an array
function isArray(obj) {
  return (typeof obj == "object") && (Object.getPrototypeOf( obj ) === Array.prototype);
}
// copy the attributes from original into dest
function copy_attributes(original, dest) {

  for(var i in original) {

    if(isArray(original[i])) {

      dest[i] = JSON.parse(JSON.stringify(original[i])); // copy
    }
    else if(isObject(original[i])) {

      copy_attributes(original[i], dest[i]);
    }
    else {

      dest[i] = JSON.parse(JSON.stringify(original[i])); // copy
    }
  }
};

3 Comments

Ok, what do you mean with the recursive? any example?
args = args || defaults; sets args to args if args is not false, else it sets args to defaults.
@Mr.Web: the function copy_attributes should help if your defaults variable contains sub-elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.