- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.13 Simulating Named Arguments with Destructuring
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 {}