# Optional parameter handling in JavaScript functions

This post looks into handling of default function parameter values.

ES5 JavaScript doesn’t have a built-in way to handle default parameters, the
parameter needs to be treated like any old variable.

Our dumb test function:

```js
const colorizer = function (element, color) {
  document.getElementBtId(element).style.color = color
}
```

Will give an element a color: `js» colorizer('#foo', 'rgb(255, 0, 0)')`.

Out task is to give the `color` parameter a default value.

## Ask for it, politely

Nothing happens and user get notified of it:

```js
const colorizer = function (element, color) {
  if (!color) {
    console.log('The color arg is missing')
    return false
  }

  document.getElementBtId(element).style.color = color
}
```

The following, perhaps more friendly example, gives it a default value of
`Pink`:

```js
const colorizer = function (element, color) {
  const elementColor = color || 'Pink'
  document.getElementBtId(element).style.color = elementColor
}
```

These all will fail if the parameter is needed to be `false`, `0`, or any falsy
value.

## Do explicit type checking

If the parameter might also be a falsy value, check the type first with
`typeof`:

```js
const colorizer = function (element, color) {
  // Explicitly checking: use default value if undefined
  color = typeof color === 'undefined' ? 'Pink' ? color
  document.getElementBtId(element).style.color = color
}
```

## The ES6 default parameter value

ECMAScript 6 (the JavaScript language specification) supports default values out
the box:

```js
const colorizer = function (element, color = '#BADA55') {
  document.getElementBtId(element).style.color = color
}
```

### Gotchas with the ES6 default params

If our `color` happens to be `null`, the fallback value is not applied:

```js
colorizer('#foo', null)
// Errors
```

Because `null` is not really a bottom value: `typeof null` is Object.

You have to make sure your color values is never null, or use the or `||`
operator:

```js
const colorizer = function (element, color) {
  color = color || '#BADA55'
  document.getElementBtId(element).style.color = color
}
```
