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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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