I'm sure that this is relatively straightforward and that I'm missing something obvious. I'm reading through Mozilla's tutorials on ES6, and their chapter on destructuring contains the following pattern:
FUNCTION PARAMETER DEFINITIONS
As developers, we can often expose more ergonomic APIs by accepting a single object with multiple properties as a parameter instead of forcing our API consumers to remember the order of many individual parameters. We can use destructuring to avoid repeating this single parameter object whenever we want to reference one of its properties:
function removeBreakpoint({ url, line, column }) { // ... }
This is a simplified snippet of real world code from the Firefox DevTools JavaScript debugger (which is also implemented in JavaScript—yo dawg). We have found this pattern particularly pleasing.
What I don't understand is how this relates to destructuring. Is the idea that you permit the ability to pass an object into this function that can be in arbitrary order as long as it contains all items, i.e. { line: 10, column: 20, url: 'localhost' }
?
If so, what is the benefit over something like
function removeBreakpoint(params) {
// ...
}
where params is an object with url
, line
, and column
? Is the idea just that you force Javascript to validate a function's parameters when used in a destructured context by explicitly defining them?
Within
removeBreakpoint
, you can useurl
,line
, andcolumn
directly. The destructuring happens whenremoveBreakpoint
is called with an options object; that object's matching properties are destructured into individual arguments.Yes, but it doesn't have to contain all the items; if it doesn't, then since the argument is initialized from an object property that doesn't exist, the argument is
undefined
(unless a default value is specified).Simple example demonstrating the destructuring (Live Copy with ES5 translation on Babel's REPL):
Output:
Syntactic sugar. The new syntax for accepting options objects is more concise and declarative, automating a common pattern. This is particularly apparent when you combine it with default values (Live Copy):
Output:
In the above, even the options object itself is optional, which is why the last call works:
If we hadn't given a default for the options object itself, that call would have failed because we'd be trying to read the property
url
ofundefined
. Sometimes you want that, and so you'd leave the overall option off. Other times you don't.Side note: The ability to default parts of the options object and also, separately, the entire options object leads to an interesting situation where you can have different defaults depending on whether an options object was given but didn't have a specific option vs. no options object being given at all, all done declaratively: Live Copy
Output: