简体   繁体   中英

In JavaScript, how can I create a function with an optional parameter?

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

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(someParam) {
  if (someParam === undefined) {
    someParam = 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.

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...
  }

You can use annotation such as {Object=} or {number=} in the comment section when using a doclet:

/** 
 * @param {object=}xyz
 */

Modern IDE knows to recognize annotations for JavaScript and shows you indications about potential problems in your code.

Example:

/**
 *
 * @param query 
 * @param callback 
 * @param {number=} ttl optional time-to-leave
 */
 loadByJSONP:function loadByJSONP(query, callback, ttl) {
   ...do some work
 }

In this example 'ttl' is optional. the annotation {number=} indicate to IDE that this parameter is optional. Accordingly when you call this function with two parameters only, you will not get warning.

Annotations can also be used for designating the expected type. this makes your code better and less prone to bugs. Here is the link for annotations:

https://developers.google.com/closure/compiler/docs/js-for-compiler

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.

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

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.

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 _.

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>

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++) ...
// 1. best way
function sum1(x = 1, y = 2) {
    console.log(x + y)
}
sum1()  // x=1,y=2
sum1(4, 5)  // x=4,y=5
sum1(8)  // x=8,y=2

// 2. Ternary way
function sum2(x) {
    x = x !== undefined ? x : 1; // if x define x=x, if undefine x=1
    console.log(x)
}
sum2(1)
sum2(5)
sum2('foo')
sum2()


// logical way
function sum3(x) {
    x = x || 1;  // x = either x if x is true or 1 if x is not false
    console.log(x)
}
sum3(1)
sum3(5)
sum3('foo')
sum3()

For history sake: You can loop in your arguments with a != null check. For instance :

function container(param1, param2, param3, param4){
    var param1, param2, param3, param4 = 0 // or other data types.
    for (var i = 0; i < arguments.length; i++){
       if(i != null) {
       console.log(i); // or put default values to your parameters if you need to.
    }
}

Now, all arguments become optional.

function connect(hostname, port, method) {
   hostname = hostname || "localhost";
   port = port || 80;
   method = method || "GET";
}

Important URL Optional Parameters in Javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM