Lesson 16. Destructuring parameters

 

After reading lesson 16, you will

  • Know how to destructure array parameters
  • Know how to destructure object parameters
  • Know how to simulate named parameters
  • Know how to create aliased parameters

In lesson 11 you learned about destructuring objects and arrays. These same principles can be used directly within the parameter list of a function. This makes array and object parameters easier to deal with and more self-documenting, and opens the door for useful techniques such as simulating named parameters.

Consider this

The following function takes three parameters. How would you go about making all of the parameters optional so the function could be called setting only the necessary values? For example, what if you only wanted to set the height and use a default width? How would the caller of the function specify that it just wants to specify the height? By name? What if it got the name wrong? For example, the caller might use h when the full word height was required.

function image(src, width, height) {
  // build image

}

16.1. Destructuring array parameters

Imagine you’re writing a program to compare the differences between two files. You’re using a library that provides a diff function that takes two strings and computes the difference between them. It returns an array with three values. The first value is the text that has been added. The second is the text that has been removed, and finally the third value is the text that has been modified.

16.2. Destructuring object parameters

16.3. Simulating named parameters

16.4. Creating aliased parameters

Summary