DEV Community

Cover image for TIL: Destructuring Property Assignment
Nicholas Jamieson
Nicholas Jamieson

Posted on • Updated on • Originally published at ncjamieson.com

 

TIL: Destructuring Property Assignment

This article was originally published on my blog.


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
console.log("assigning")
({ name } = { name: "Alice" })

Will effect this error:

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

Title photo by Florian Klauer on Unsplash.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!