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.

1
  • To me the MDN documentation implies that you can do what you were attempting. Commented Jan 9, 2015 at 16:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

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: 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).
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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.