clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Optional parameter handling in JavaScript functions

Filed under: JavaScript— Tagged with: functional

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:

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

Will give an element a color: 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:

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:

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:

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:

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:

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:

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

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!