Why was destructuring introduced to ECMAScript 6?
Asked
Active
Viewed 104 times
-2
-
1There seem to be two different questions here. Are you looking for "compelling use cases" or an explanation/justification for the example code? – Matt Ball Oct 11 '14 at 17:54
-
Compelling use cases – Sam Leach Oct 11 '14 at 17:55
-
1@SamLeach You might want to check [these examples](http://wiki.ecmascript.org/doku.php?id=harmony:destructuring#examples) out – thefourtheye Oct 11 '14 at 18:05
-
I have edited the question to be a specific question. – Sam Leach Oct 12 '14 at 18:42
-
It's still not a very good question for SO. To get information about *why* a certain feature was added to a language or why it works that way, you have better chances getting an answer from the people working on the language. E.g. https://esdiscuss.org/ – Felix Kling Oct 12 '14 at 18:55
3 Answers
4
Trivial example:
var {forEach} = Array.prototype;
forEach.call(document.querySelector(...
Argument destructuring is fun:
function ({opt1 = true, opt2 = false, opt3} = {}) { ...
-
-
-
Yes, this works not only in argument lists, but in general: `var { x = 3 } = {};`. – Oct 12 '14 at 07:22
-
1Here's your useless destructuring brain-teaser of the day: what does `var {x} = 1;` do? TypeError? Or...? – Oct 12 '14 at 07:26
-
@torazaburo `undefined` most likely. `typeof (1).x == "undefined"` – lyschoening Oct 30 '14 at 08:34
4
Here is another one: Map#entries
returns an iterator over (key, value)
tuples. The most elegant way to iterate over them is use destructuring:
for (var [key, value] of map.entries()) {
// ...
}

Felix Kling
- 795,719
- 175
- 1,089
- 1,143
2
not sure why I would want to use
[x, y] = [y, x]
.
Because using an extra variable two swap two values is cumbersome, and JS with its pass-by-value function calls does not let you write a swap
function.
most compelling use cases for ECMAScript 6's destructuring feature?
What I can think of, this mostly will be used for
multiple function return values
function rgb2hsv(r, g, b) { … return {h, s, v}; } … var {h, s, v} = rgb2hsv(…);
Promise.spawn(function* () { … var [a, b] = yield [async1(), async2()]; … })
importing modules, e.g. something like
var {abs, trunc, round} = require('Math')