TIL: Destructuring Property Assignment

December 22, 2019 • 1 minute read

Typewriter parts
Photo by Florian Klauer on Unsplash

Until recently, I wasn’t aware of the JavaScript syntax for destructuring property assignment.

I knew that I could destructure array elements and object properties in variable declarations, like this:

const [vowel] = ["a", "e", "i", "o", "u"];
console.log(vowel); // a

const { name } = { name: "Alice" };
console.log(name); // Alice

And I knew that I could destructure an array and assign an element to a previously declared variable, like this:

let vowel;
[vowel] = ["a", "e", "i", "o", "u"];
console.log(vowel); // a

But I didn’t know how to destructure an object and assign a property to a previously declared variable. I tried this:

let name;
{ name } = { name: "Alice" };

But this error was effected:

SyntaxError: Unexpected token '='

The problem was that the braces surrounding the name variable were parsed as a block. To be parsed as destructuring property assignment, the assignment expression needs to be surrounded by parentheses, like this:

let name;
({ name } = { name: "Alice" });
console.log(name); // Alice

It’s worth noting that if you rely upon automatic semicolon insertion, you may need to precede the parentheses with a semicolon to prevent the assignment expression from being used to execute a function on the previous line.

For example, this usage:

let name
({ name } = { name: "Alice" })

Will effect this error:

TypeError: console.log(...) is not a function

Nicholas Jamieson’s personal blog.
Mostly articles about RxJS, TypeScript and React.

© 2020 Nicholas Jamieson All Rights ReservedRSS