Moshe's Blog

Tips and tricks learnt along the way.

Handling Optional Args in JS

| Comments

Often times I find myself writing functions which have optional args, while it’s generally a better idea to pass an options object instead for mutliple arguments, three (maybe four) can still be considered an acceptable arity.

Let’s take a simple signature and implement some optional args.

1
function require(name, deps, fn) {}

The way I started to deal with cases like this is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function require(name, deps, fn) {
  var args = [].slice.call(arguments);

  if (typeof args[0] !== 'string') {
    args.splice(0, 0, null);
  }

  if (!(args[1] instanceof Array)) {
    args.splice(1, 0, []);
  }

  if (typeof args[2] !== 'function') {
    args.splice(2, 0, function() {});
  }

  [name, deps, fn] = args; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

}

I find this the clearest way to deal with optional args and I find the logic very easy to follow.

Comments