Default Arguments for Functions

// Combiner of passed arguments and defaults (usable with any function)
Object.prototype.combine = function(_args){
  for(var i in this) {
    if(typeof _args[i] == "undefined") {
      _args[i] = this[i];
    }
  }
};

// Specific example function with defaults
function feedTheCat(args){
  var defaults = {
      'morning' : "nothing",
      'noon'    : "pork",
      'nite'    : "mouse"
  };
  defaults.combine(args);
}

// USAGE: only passing 2 of 3 arguments
feedTheCat({
  'morning': "milk", 
  'nite': "kitekat"
}); 

// Values would be: milk | pork | kitekat

Comments

  1. User Avatar
    Benicio

    Thanks, perfect solution.

  2. User Avatar
    vitkon
    Permalink to comment#

    or $.extend in jQuery

  3. User Avatar
    Reza Baiat
    Permalink to comment#

    FIX BUG!

    <script type="text/javascript">
    Object.prototype.combine = function(_args){
       for(var i in this) {
          if(typeof _args[i] == "undefined") {
                   this[i] = _args[i];    // BugFix: assignment parts are swapped
          }
      }
    };
    </script>
    
  4. User Avatar
    Costica
    Permalink to comment#

    Is preferably to not use an prototype for Object, you will have issues when will try to foreach it, this prototype will appear in the list of all objects and you will have to use hasOwnProperty to omit it, so better use simple functions.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag