16

let's say I call use this syntax in es6:

let a, b;

{a, b} = { a: 100, b: 300 };

the code will run without error;

but let's rewrite is like this:

function fn() {
    return { a: 100, b: 200 }
}

let a, b;

{ a, b } = fn();

when I run the code above, it says unexpected token "="; I am a little confused, what is the difference?

joknawe
  • 1,510
  • 11
  • 15
碳60
  • 173
  • 1
  • 7
  • `run the code` where? FF, Chrome, Safari, Edge?! – hellow Jul 02 '18 at 11:44
  • it doesn't matter where it runs, you can try any of the enviroment you mentioned – 碳60 Jul 02 '18 at 12:22
  • None of your examples work for me, but if I do instead `var {a, b} = fn()` (note var instead of let) it works (and if I put both in the same line) – hellow Jul 02 '18 at 12:34
  • @hellow yes that will work too, see my answer below. let vs. var not making a difference here - having on same line is. – joknawe Jul 02 '18 at 12:43

3 Answers3

24

Add round braces: ({ a, b } = fn());

From Mozilla documentation:

The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

joknawe
  • 1,510
  • 11
  • 15
0

Wrap the object assignment in parenthesis

({a ,b} = fn());
-3

Use a,b instead of {a,b}:

let a, b;
a,b = { a: 100, b: 300 };


function fn() {
    return { a: 100, b: 200 }
}

let a, b;
a,b = fn();
Rupinder
  • 24
  • 3
  • 4
    it is not, in your solution, a is undefined, and b is { a: 100, b: 200 }, that is not my expectation – 碳60 Jul 02 '18 at 12:20