views:

227

answers:

8

Question: What is the proper way to define a function in JavaScript that takes optional parameters?

For example:

function myFunc(optionVar1) {
    if(optionVar1 == undefined) {
        ...
    } else {
        ...
    }
}

myFunc('10');  // valid function call
myFunc();      // also a valid function call

Is it proper to use a ? mark like Ruby in the function declaration like so to denote optional parameters:

function myFunc(optionVar1?) {...}  //  <--- notice the ? mark
+2  A: 

The first google response I discovered:

http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions

I haven't seen any instances where a question mark is used to alert a caller to an optional parameter. While it's done in other languages, I don't think it's necessary in javascript.

In fact, it seems that you can't use a question mark in the variable name. Only letters, numbers, $ and _.

Damovisa
Article is of no help unfortunately.
SeanD
Sorry, I've updated my answer.
Damovisa
What a pity. Which the argument declaration allowed denoting which parameter are and aren't required.
SeanD
Wish* (not which)
SeanD
Might as well linked it with http://letmegooglethatforyou/ :D
nicerobot
+10  A: 

There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren't specified they're undefined so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:

function myfunc(someVar) {
  if (someParam === undefined) {
    someVar = 10;
  }
  ...
}

Also you can access the parameters programmatically using the arguments property.

Lastly, if you have more than about 3-4 parameters it's generally advisable to use an anonymous object instead.

cletus
A: 

Just don't define the function with any parameters and access the special arguments array from within the function where you want the optional parameters to be. Example below.

<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
function foo() {
  var argv = foo.arguments;
  var argc = argv.length;
  for (var i = 0; i < argc; i++) {
    alert("Argument " + i + " = " + argv[i]);
   }
}
</SCRIPT>
</HEAD>
<BODY onload="foo('hello', 'world');">
</BODY>
</HTML>
James
This doesn't help people know what parameters should be included though. Seems kludgy
SeanD
nothing a nice function comment can't handle :p
James
+2  A: 

Actually, all parameters are optional in JS functions. There is no warning or error if you omit a parameter.

You can set defaults like

function throw_cat(dist){
  dist = typeof dist=='undefined' ? 20 : dist;
   //OR
  dist = dist || 20; //this will assign it to 20 if you pass 0 or another 'falsy' value, though. May be good if you expect a string. String '0' stays, '' or null assigns the default
  //etc...
  }
Alex JL
`typeof` returns a String. Use `typeof dist==='undefined'`, or, my preference, just `dist===undefined`.
bobince
Thanks, I'm a bit unclear on that. In some contexts (i.e. outside a function), doing `if(randomvar==undefined)` produces an error - `ReferenceError: randomvar is not defined` so I go with typeof. I'll add the quotes.
Alex JL
+1  A: 

Some sources will tell you to skip parameters altogether and instead make use of the arguments array. This lets you take any input that's provided to your function, and you can decide how to respond to the arguments passed to your function as you see fit.

You can read more about it here: http://www.devguru.org/technologies/ecmascript/quickref/arguments.html

Frank DeRosa
+1  A: 

cletus and Damovisa have made good suggestions. I would also add that some (like myself) might prefer a notation like this:

function foo(/*bar*/) {
   if (arguments.length == 1) {
      var bar = arguments[0];
      ...
   }
}

This serves to document to developers of your code base that the argument is optional and also documents the name, but it also prevents the argument from showing up in the function name in a debugger (the example would show up as foo() rather than foo(optional_argument). Otherwise, developers who are consuming the API might assume that it was required.

Edit: This is especially useful for optional arguments that are intended to be used internally.

Bryan Matthews
A: 

Is it proper to use a ? mark like Ruby in the function declaration

No, there's no language-based way denote an optional arg. I definitely think it's worth indicating in a comment, though:

function myFunc(var1, var2 /* optional */, var3 /* optional */) {
    if (var2===undefined) ...

(Note the triple-equals for exact equality testing. Otherwise a passed null value will also match. You generally want === for most comparisons in JS, as the double-equals is undesirably weakly-typed.)

For when you've got an indeterminate number of optional arguments, you generally omit them from the function statement, and again a comment is polite:

function myFunc(var1 /* , optional var2..varN */) {
    for (var i= 1; i<arguments.length; i++) ...
bobince
+1  A: 

First, everyone who writes JavaScript, do yourself a favor and go through Learning Advanced JavaScript from John Resig.

function myFunc(arg1, arg2 /* varargs... */) {
  var optional = Array.prototype.slice.call( arguments, 2 );

Every parameter to a function is "optional", even those you declare in the parameter list of the function declaration.

Just consider documenting them well.

nicerobot