Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 751
SeanD Avatar asked Feb 09 '10 00:02

SeanD


People also ask

How do you make a function parameter optional?

Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.

How do you specify an optional parameter?

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.

How do you make a function parameter optional in TypeScript?

Use a question mark to set an optional parameter in a function in TypeScript, e.g. function sum(a: number, b?: number) {} . If set to optional, the parameter can have a type of undefined or the specified type, because unspecified parameters get the value undefined . Copied!


2 Answers

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.

like image 184
cletus Avatar answered Sep 29 '22 18:09

cletus


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...   } 
like image 35
JAL Avatar answered Sep 29 '22 17:09

JAL