Using JavaScript objects for function arguments with default values

Here’s an example of passing arguments to a JavaScript function using an object, which provides several advantages: each argument is optional and has a default value if it’s not supplied, arguments are named (making your code more readable), and arguments are position-independent (so you don’t have to remember an obscure ordering).

So if you had a function that took three integers (a,b,c) you might normally call like this:

myfunction(22, 3, 5);

You can instead call it like this (letting ‘b’ take the default value):

myfunction({ c:5, a:22  });

Then in the function you could set the defaults and decode the arguments in a few lines of code:

function myfunction(passedArgsObj) {
  /* defaults */
  args = { a:1, b:2, c:3 };
  /* override the defaults if necessary */
  for (var argName in passedArgsObj) {
    args[argName] = passedArgsObj[argName];
  }
  alert("a = "+args.a);
  alert("b = "+args.b);
  alert("c = "+args.c);
}

Update

Here’s a slightly cleaner version:

function myfunction() {
  var args = { a:1, b:2, c:3 };
  for (var n in arguments[0]) { args[n]=arguments[0][n]; }
}

One Response to “Using JavaScript objects for function arguments with default values”

  1. [...] See also: Using JavaScript objects for function arguments with default values [...]

Leave a Reply