Reputation: 305
I had a problem running this piece of code here when it was saved to a text file and ran with node in the command line.
let x;
{k1: x = null } = {k1: "Hello"};
console.log(x);
Running this would throw an error at the assignment operator being invalid.
However, when the code is directly input into the node interpreter, it'll print out "Hello"
which is what I'm expecting.
Anyone know what this could be? The idea is to construct a class with default values and update the class using the same method, reusing the current values when something is missing.
Upvotes: 1
Views: 1018
Reputation: 40444
You have to use assignment wihout declaration
let x;
({k1: x = null } = {k1: "Hello"});
or just:
let { k1: x = null } = { k1: "Hello" };
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}
NOTE: Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
Upvotes: 1