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?
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?
Share Improve this question edited Jul 2, 2018 at 12:58 joknawe 1,54012 silver badges16 bronze badges asked Jul 2, 2018 at 11:39 碳60碳60 1731 silver badge7 bronze badges 4 |3 Answers
Reset to default 24Add 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
Wrap the object assignment in parenthesis
({a ,b} = fn());
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();
run the code
where? FF, Chrome, Safari, Edge?! – hellow Commented Jul 2, 2018 at 11:44var {a, b} = fn()
(note var instead of let) it works (and if I put both in the same line) – hellow Commented Jul 2, 2018 at 12:34