Skip to content Skip to sidebar Skip to footer

Node JS / V8 Destructuring Bug?

Using node 8.4.0: $ node > {x, y} = {x: 1, y: 2} { x: 1, y: 2 } > However, the following errors also non interactive: (the only diff is the semicolon) $ node > {x, y} = {

Solution 1:

The proper syntax to destructure an object to existing variables is

({x, y} = {x: 1, y: 2});

This allows {x, y} = {x: 1, y: 2} to be an expression. Otherwise {x, y} is interpreted as a block with comma operator, this results in Unexpected token = error.

It works without parentheses and a semicolon in console because it is treated as an expression there. This is efficiently same thing as

console.log({x, y} = {x: 1, y: 2});

Solution 2:

It is not a bug but by design. See "Assignment without declaration":

A variable can be assigned its value with destructuring separate from its declaration.

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

The ( .. ) 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}


Post a Comment for "Node JS / V8 Destructuring Bug?"