2

Why is this not valid when using the new es6 destructuring syntax

var a, b, c;
{a, b, c } = {a:1, b:2, c:3};

when this is:

var {a, b, c } = {a:1, b:2, c:3};
console.log(a, ' ', b, ' ',c);

and so is this:

var a = 1;
var b = 3;

[a, b] = [b, a];

I had a read of the MDN documentataion and I see no mention of the syntax I'm attempting and I assume there must be a good reason, I'm just trying to understand why.

Raoul
  • 2,043
  • 1
  • 21
  • 29
  • To me the MDN documentation implies that you *can* do what you were attempting. – JMM Jan 09 '15 at 16:23

1 Answers1

4

In your example, the first { is ambiguous and the parser will interpret it as the beginning of a block. While {a, b, c} is a valid block, the following assignment operator is not valid.

Wrap everything in parenthesis and it will parse correctly:

({a, b, c} = {a:1, b:2, c:3});

Example


This is similar to having an object literal by itself (for whatever reasons):

{"a": 42}   // parse error
({"a": 42}) // works
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • With traceur I get `Invalid left-hand side in assignment` when doing that. `({a, b, c} = {a: 1, b: 2, c: 3});` works for me. – JMM Jan 09 '15 at 16:15
  • @JMM: Yeah, I had that before, but esprima is parsing the my case correctly. I actually don't know what's correct. I guess wrapping everything in parenthesis is safer (updated). – Felix Kling Jan 09 '15 at 16:16
  • 1
    Ok, I thought you did, then I looked again and it was different but didn't show an edit -- I guess it does that when an edit happens before a certain timeout. It's worth noting that the MDN article @Raoul linked to implies that you can do just what he was trying to do. – JMM Jan 09 '15 at 16:18
  • Oh, I see. I didn't look at the article. I don't know if it is supposed to work at some point, I guess it depends on the parser. – Felix Kling Jan 09 '15 at 16:21
  • 1
    Aha, that makes complete sense, I was so busy thinking about the new syntax I forgot to think about basic parsing rules :) This works perfectly in 6to5 also. Thanks. – Raoul Jan 09 '15 at 16:48