Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment cause error: "unexpected token ="

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?

like image 924
碳60 Avatar asked Jul 02 '18 11:07

碳60


People also ask

How do I fix unexpected token error?

As you write your JavaScript application, the unexpected token error always occurs because JavaScript expected a specific syntax that's not fulfilled by your current code. You can generally fix the error by removing or adding a specific JavaScript language symbol to your code.

What is unexpected token error?

The JavaScript exceptions "unexpected token" occur when a specific language construct was expected, but something else was provided. This might be a simple typo.

What is Destructuring assignment?

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.

What is Destructure?

To destroy the structure of something. To dismantle.


1 Answers

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

like image 155
joknawe Avatar answered Sep 21 '22 14:09

joknawe