Tip 29: Access Object Properties with Destructuring

Managing excessive parameters

In the previous tip, you learned how to create default parameters, which are a great addition to the language, but they still have one big problem: Parameters always have to be given in order. If you wanted to specify the third parameter but you didn’t care about the second, you’d still be forced to enter a value. Default parameters aren’t helpful if you want to skip a parameter.

What about situations where you need a large number of arguments for a function? What about situations where you know that the needs of functions are likely to change? In JavaScript, most developers add extra arguments to an object and pass the object as the last parameter to a function.

Example

For example, what if you wanted to display a number of photos and needed to translate the values into an HTML string? Specifically, you want to include the image, title, photographer, and location in that order in your string, but you also want any additional information. Some photographs include equipment, image type, lenses information, and any other customizations. You don’t know what it all will be, but you still want to display it.

There is a lot of information associated with a photograph. Passing that information as individual parameters would be excessive—you could end up with about ten parameters. Besides, the information is already structured. What’s the point in changing it? Here’s an example of some information about a photograph.

Get hands-on with 1000+ tech skills courses.