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

Reference URL

Comments

  1. Benicio

    Thanks, perfect solution.

  2. vitkon
    Permalink to comment#

    or $.extend in jQuery

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

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```

We have a pretty good* newsletter.