Multiple arguments vs. options object

JavascriptJsonFunctionObjectArguments

Javascript Problem Overview


When creating a JavaScript function with multiple arguments, I am always confronted with this choice: pass a list of arguments vs. pass an options object.

For example I am writing a function to map a nodeList to an array:

function map(nodeList, callback, thisObject, fromIndex, toIndex){
    ...
}

I could instead use this:

function map(options){
    ...
}

where options is an object:

options={
    nodeList:...,
    callback:...,
    thisObject:...,
    fromIndex:...,
    toIndex:...
}

Which one is the recommended way? Are there guidelines for when to use one vs. the other?

[Update] There seems to be a consensus in favor of the options object, so I'd like to add a comment: one reason why I was tempted to use the list of arguments in my case was to have a behavior consistent with the JavaScript built in array.map method.

Javascript Solutions


Solution 1 - Javascript

Like many of the others, I often prefer passing an options object to a function instead of passing a long list of parameters, but it really depends on the exact context.

I use code readability as the litmus test.

For instance, if I have this function call:

checkStringLength(inputStr, 10);

I think that code is quite readable the way it is and passing individual parameters is just fine.

On the other hand, there are functions with calls like this:

initiateTransferProtocol("http", false, 150, 90, null, true, 18);

Completely unreadable unless you do some research. On the other hand, this code reads well:

initiateTransferProtocol({
  "protocol": "http",
  "sync":      false,
  "delayBetweenRetries": 150,
  "randomVarianceBetweenRetries": 90,
  "retryCallback": null,
  "log": true,
  "maxRetries": 18
 });

It is more of an art than a science, but if I had to name rules of thumb:

Use an options parameter if:

  • You have more than four parameters
  • Any of the parameters are optional
  • You've ever had to look up the function to figure out what parameters it takes
  • If someone ever tries to strangle you while screaming "ARRRRRG!"

Solution 2 - Javascript

Multiple arguments are mostly for obligatory parameters. There's nothing wrong with them.

If you have optional parameters, it gets complicated. If one of them relies on the others, so that they have a certain order (e.g. the fourth one needs the third one), you still should use multiple arguments. Nearly all native EcmaScript and DOM-methods work like this. A good example is the open method of XMLHTTPrequests, where the last 3 arguments are optional - the rule is like "no password without a user" (see also MDN docs).

Option objects come in handy in two cases:

  • You've got so many parameters that it gets confusing: The "naming" will help you, you don't have to worry about the order of them (especially if they may change)
  • You've got optional parameters. The objects are very flexible, and without any ordering you just pass the things you need and nothing else (or undefineds).

In your case, I'd recommend map(nodeList, callback, options). nodelist and callback are required, the other three arguments come in only occasionally and have reasonable defaults.

Another example is JSON.stringify. You might want to use the space parameter without passing a replacer function - then you have to call …, null, 4). An arguments object might have been better, although its not really reasonable for only 2 parameters.

Solution 3 - Javascript

Using the 'options as an object' approach is going to be best. You don't have to worry about the order of the properties and there's more flexibility in what data gets passed (optional parameters for example)

Creating an object also means the options could be easily used on multiple functions:

options={
    nodeList:...,
    callback:...,
    thisObject:...,
    fromIndex:...,
    toIndex:...
}

function1(options){
    alert(options.nodeList);
}

function2(options){
    alert(options.fromIndex);
}

Solution 4 - Javascript

It can be good to use both. If your function has one or two required parameters and a bunch of optional ones, make the first two parameters required and the third an optional options hash.

In your example, I'd do map(nodeList, callback, options). Nodelist and callback are required, it's fairly easy to tell what's happening just by reading a call to it, and it's like existing map functions. Any other options can be passed as an optional third parameter.

Solution 5 - Javascript

I may be a little late to the party with this response, but I was searching for other developers' opinions on this very topic and came across this thread.

I very much disagree with most of the responders, and side with the 'multiple arguments' approach. My main argument being that it discourages other anti-patterns like "mutating and returning the param object", or "passing the same param object on to other functions". I've worked in codebases which have extensively abused this anti-pattern, and debugging code which does this quickly becomes impossible. I think this is a very Javascript-specific rule of thumb, since Javascript is not strongly typed and allows for such arbitrarily structured objects.

My personal opinion is that developers should be explicit when calling functions, avoid passing around redundant data and avoid modify-by-reference. It's not that this patterns precludes writing concise, correct code. I just feel it makes it much easier for your project to fall into bad development practices.

Consider the following terrible code:

function main() {
	const x = foo({
		param1: "something",
		param2: "something else",
		param3: "more variables"
	});

	return x;
}

function foo(params) {
	params.param1 = "Something new";
	bar(params);
	return params;
}


function bar(params) {
	params.param2 = "Something else entirely";
	const y = baz(params);
	return params.param2;
}

function baz(params) {
	params.params3 = "Changed my mind";
	return params;
}

Not only does this kind of require more explicit documentation to specify intent, but it also leaves room for vague errors. What if a developer modifies param1 in bar()? How long do you think it would take looking through a codebase of sufficident size to catch this? Admittedly, this is example is slightly disingenuous because it assumes developers have already committed several anti-patterns by this point. But it shows how passing objects containing parameters allows greater room for error and ambiguity, requiring a greater degree of conscientiousness and observance of const correctness.

Just my two-cents on the issue!

Solution 6 - Javascript

Your comment on the question:

> in my example the last three are optional.

So why not do this? (Note: This is fairly raw Javascript. Normally I'd use a default hash and update it with the options passed in by using Object.extend or JQuery.extend or similar..)

function map(nodeList, callback, options) {
   options = options || {};
   var thisObject = options.thisObject || {};
   var fromIndex = options.fromIndex || 0;
   var toIndex = options.toIndex || 0;
}

So, now since it's now much more obvious what's optional and what's not, all of these are valid uses of the function:

map(nodeList, callback);
map(nodeList, callback, {});
map(nodeList, callback, null);
map(nodeList, callback, {
   thisObject: {some: 'object'},
});
map(nodeList, callback, {
   toIndex: 100,
});
map(nodeList, callback, {
   thisObject: {some: 'object'},
   fromIndex: 0,
   toIndex: 100,
});

Solution 7 - Javascript

It depends.

Based on my observation on those popular libraries design, here are the scenarios we should use option object:

  • The parameter list is long (>4).
  • Some or all parameters are optional and they don’t rely on a certain order.
  • The parameter list might grow in future API update.
  • The API will be called from other code and the API name is not clear enough to tell the parameters’ meaning. So it might need strong parameter name for readability.

And scenarios to use parameter list:

  • Parameter list is short (<= 4).
  • Most of or all of the parameters are required.
  • Optional parameters are in a certain order. (i.e.: $.get )
  • Easy to tell the parameters meaning by API name.

Solution 8 - Javascript

Object is more preferable, because if you pass an object its easy to extend number of properties in that objects and you don't have to watch for order in which your arguments has been passed.

Solution 9 - Javascript

For a function that usually uses some predefined arguments you would better use option object. The opposite example will be something like a function that is getting infinite number of arguments like: setCSS({height:100},{width:200},{background:"#000"}).

Solution 10 - Javascript

I would look at large javascript projects.

Things like google map you will frequently see that instantiated objects require an object but functions require parameters. I would think this has to do with OPTION argumemnts.

If you need default arguments or optional arguments an object would probably be better because it is more flexible. But if you don't normal functional arguments are more explicit.

Javascript has an arguments object too. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopheView Question on Stackoverflow
Solution 1 - JavascriptJeremy J StarcherView Answer on Stackoverflow
Solution 2 - JavascriptBergiView Answer on Stackoverflow
Solution 3 - JavascriptFluidbyteView Answer on Stackoverflow
Solution 4 - JavascriptTrevor DixonView Answer on Stackoverflow
Solution 5 - JavascriptajxsView Answer on Stackoverflow
Solution 6 - JavascriptIzkataView Answer on Stackoverflow
Solution 7 - JavascriptLynn NingView Answer on Stackoverflow
Solution 8 - JavascripthappyCodaView Answer on Stackoverflow
Solution 9 - JavascriptIlya SidorovichView Answer on Stackoverflow
Solution 10 - Javascriptdm03514View Answer on Stackoverflow