-1

Why was destructuring introduced to ECMAScript 6?

Sam Leach
  • 12,076
  • 8
  • 39
  • 71
  • 1
    There 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 Answers3

4

Trivial example:

var {forEach} = Array.prototype;
forEach.call(document.querySelector(...

Argument destructuring is fun:

function ({opt1 = true, opt2 = false, opt3} = {}) { ...
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
  • 705,106
  • 160
  • 1,004
  • 1,072
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')
    
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164