Design & Download
Your JS Library
in Seconds!!!

Snippet: Setting Default Values for Functions

Written by Christopher West (cwest) on December 04, 2015.
function setDefaults(fn) {
  var defaults = slice(arguments, 1);
  return function() {
    var args = slice(arguments), i = args.length;
    for (args = args.concat(slice(defaults, i)); i--;) {
      if (args[i] === undefined) {
        args[i] = defaults[i];
      }
    }
    return fn.apply(this, args);
  };
}

In ES6, the ability to set default parameters has finally been added to JavaScript:

function sayHello(name = "world") {
  alert("Hello " + name + "!");
}

Unfortunately, not all environments support this behavior so an alternative is to use YourJS.setDefaults(fn, ...defaults):

var sayHello = YourJS.setDefaults(function(name) {
  alert("Hello " + name + "!");
}, "world");

One difference between this workaround and the ES6 solution is the fact that the defaults are evaluated every time in ES6 whereas they are executed once and only once in this version. Therefore this solution works more like the default parameters of Python.

setDefaults() API Documentation

Description

Sets the default value of each specified parameter in the given function.

Parameters

  1. fn {Function}:
    The function whose default parameters will be set.
  2. ...defaults {...*}:
    Each subsequent parameter will be used as the default parameter for fn.

Returns

Returns a function whose default parameters are set with those passed in as ...defaults. NOTE: If undefined is passed into this returned function, the default value will be used instead.