Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

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

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 in triple backtick fences like this:

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