bounding brokenness

Using object destructuring to implement named parameters in JavaScript

One of the neat things about JavaScript 1.7 and up is the support for array destructuring. It allows you to do things like

function foo() { return [5, 10]; }
let [a, b] = foo();
or even
function bar([a, b]) { return a + b; }
bar([5, 10]);
While the first example is obviously useful, the second one is somewhat less so. However, I didn’t know just how useful the general idea behind the second example is until this weekend, when asuth pointed out on IRC something I’d been previously unaware of: JavaScript supports object destructuring too. This means that you can do stuff such as
function baz() { return {a: 5, b: 10}; }
let {a: x, b: y} = baz();
Here, x and y will be 5 and 10 respectively at the end.

And yes, you can even write

function quux({a: x, b: y}) { return x + y; }
quux({a: 5, b: 10});
This looks like a great way to implement named parameters for your functions whenever you need them.

But wait – there’s more! There’s even a shorthand for when the property name is the same as the name of the variable you want to assign to. The last example could be rewritten as

function quux({a, b}) { return a + b; }
quux({a: 5, b: 10});
Depending on your use case, this might be an even better way to implement named parameters!

Note that the shorthand only works for destructuring assignments – you can’t use it to create (or “structure”) objects.