Tip 29: Access Object Properties with Destructuring
Explore how to improve JavaScript function parameter handling by using destructuring assignment. Understand how to extract values from objects, set default values, collect leftover properties with the rest operator, and assign keys to different variable names. This lesson teaches techniques to simplify code, clean up function parameters, and work effectively with object and array destructuring.
We'll cover the following...
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.
Pulling information from objects
In this case, it makes sense to pass the whole photo object directly into a function. Of course, once you have it in the function, what do you do with it?
You can either pull the information directly from the object when needed using dot syntax— ...