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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".