Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters in JavaScript [duplicate]

Tags:

javascript

Question

What is a good way of assigning a default value to an optional parameter?

Background

I'm playing around with optional parameters in JavaScript, and the idea of assigning a default value if a parameter is not specified. My method in question accepts two parameters, the latter of which I deem to be optional, and if unspecified should default to false. My method looks something like this...

// selects the item, appropriately updating any siblings
// item to select [, toggle on / off]
this.selectItem = function(item, toggle)
{
    toggle = toggle && typeof toggle === 'boolean';
    if (toggle)
    {
       // ...
    }
}

Testing

After running a few tests on this jsFiddle, using the following principal for default value assigning:

function checkParamIsBoolean(param)
{
    param = param && typeof param === 'boolean';
}

checkParamIsBoolean('me'); // boolean
checkParamIsBoolean([]); // boolean
checkParamIsBoolean(true); // boolean
checkParamIsBoolean(false); // boolean
checkParamIsBoolean(1 == 1); // boolean
checkParamIsBoolean(1); // boolean
checkParamIsBoolean(null); // object
checkParamIsBoolean(undefined); // undefined
​

As you can, the results vary, and aren't desired.

Expected

null = false
undefined = false

Actual

null = object
undefined = undefined

Summary

Are there any alternative approaches to assigning a default value to an optional parameter if it's unspecified; would it be better to use _toggle as the parameter and then assign the value to var toggle within the method?

like image 477
Richard Avatar asked Jun 14 '12 09:06

Richard


People also ask

Can we pass optional parameters in JavaScript?

To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.

Are parameters always optional in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.

What happens if you pass an extra parameter to a method in JavaScript?

Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.

Can parameters be optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.


3 Answers

Better solution is to use named arguments wraped in a object. It keeps your code clean and prevents errors in case of complex functions (with many default and non-default arguments). Otherwise you need to remember about the order of arguments and assign default values based on the types of arguments present (that's what you're trying to do).

That method is a primary way of passing params jQuery and jQuery's plugins.

function test(options) {     // set up default options    var defaults = {      param1:      'test',      param2:      100   };     // combine options with default values   var options = $.extend({}, defaults, options); // If you're not using jQuery you need different function here    alert(options.param1)   alert(options.param2)  }  test({'param2': 200}) // Call the function with just the second param 
like image 184
Mariusz Jamro Avatar answered Oct 12 '22 23:10

Mariusz Jamro


You can use this construction for optional parameters in your code:

//...
optionalParam = optionalParam || 'some default value';

In your concrete exaple it would be something like this:

this.selectItem = function(item, toggle)
{
    toggle = toggle || false;
   // ...
}

But in your case you could use toogle (optional parameter) directly in if statement (since you only want to check for its existence. Or optionally you could enforce boolean value like this toogle = !!toogle (double negation).

like image 34
sbgoran Avatar answered Oct 13 '22 01:10

sbgoran


A very simple way to check if toggle is undefined, and if it is then set a default value:

if (toggle === undefined) toggle = "<your default value>";

Note that this does not change toggle if it is specified but of another type than what you expected.

like image 39
Simon Forsberg Avatar answered Oct 12 '22 23:10

Simon Forsberg