Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.13 Simulating Named Arguments with Destructuring

cat.jpg

JavaScript has no “named argument” feature where you provide the parameter names in the call. But you can easily simulate named arguments by passing an object literal:

const result = mkString(values, { leftDelimiter: '(', rightDelimiter: ')' })

That is easy enough for the caller of the function. Now, let’s turn to the function implementation. You can look up the object properties and supply defaults for missing values.

const mkString = (array, config) => {
  let separator = config.separator === undefined ? ',' : config.separator
  . . .
}

However, that is tedious. It is easier to use destructured parameters with defaults. (See Chapter 1 for the destructuring syntax.)

const mkString = (array, {
    separator = ',',
    leftDelimiter = '[',
    rightDelimiter = ']'
  }) => {
  . . .
}

The destructuring syntax { separator = ',', leftDelimiter = '[', rightDelimiter = ']' } declares three parameter variables separator, leftDelimiter, and rightDelimiter that are initialized from the properties with the same names. The defaults are used if the properties are absent or have undefined values.

It is a good idea to provide a default {} for the configuration object:

const mkString = (array, {
    separator = ',',
    leftDelimiter = '[',
    rightDelimiter = ']'
  } = {}) => {
  . . .
}

Now the function can be called without any configuration object:

const result = mkString(values) // The second argument defaults to {}
  • + Share This
  • 🔖 Save To Your Account