Question: 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](http://jsfiddle.net/nLAAt/2/), 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?

Answer: 
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.
Why do you check the parameter to be boolean, if you expect an other result? The usual way would be checking for `typeof toggle != "undefined"`, but in your case

```
toggle = Boolean(toggle);

```

should do the task. You can also use the shortcut `!!toggle`, or use it directly in the if-clause:

```
if (toggle) { // will evaluate to "false" for undefined
    ...

```

BTW, no need for a `_toggle` parameter; you can just reassign to `toggle`.