Deconstructing JavaScript destructuring

Eduard Kyvenko
2 min readMay 23, 2017

--

JavaScript is like one of your favorite games, easy to pick up and hard to master. It seems like the irony of the Bushnell’s Law will haunt us with every new spec. Despite the fact that ES6 was a huge step forward for the language, it introduced a lot of new concepts with many hidden caveats.

Destructuring is the second most used feature of ES6 according to JavaScript Developer Survey Results from 2015. Of course, I’m sloppy with the stats, but these numbers are unlikely to change significantly.

Historically I perceived it as a logical evolution of object Property accessors, where destructuring is performed on properties accessible via Dot notation.

In other words, properties must be valid JavaScript identifiers.

const { bacon } = { eggs: '🍳', bacon: '🥓', bread: '🍞' }

Not quite right!

Property name as invalid identifier and destructuring

The property name is not supposed to be a valid identifier, and it can be pretty much anything, as long as it can be type cast with the toString method.

{ '🍺 + 🍺': '🍻' }

Those properties can be used in destructuring too!

const { '🍺 + 🍺': beers } = { '🍺 + 🍺': '🍻' }

It is impossible to define a variable with an invalid identifier, but you can rename it!

Computed properties

As simple as that, you can now literally destructure everything! There’s also a neat little way to use Computed property keys for objects with dynamic keys.

const RECIPE = '🍟';
const { [RECIPE]: ingredient } = { '🍟': '🥔' };

We are yet to find a chance to use this feature in the practical world, but be warned!

Should anyone use all of these?

Most likely no, but it’s healthy to be aware of poorly documented pitfalls in a programming language.

Almost the entire spectrum of destructuring capabilities in JavaScript is described in a dedicated

Check out the chapter on Destructuring from the book by Axel Rauschmayer, where he covers the entire spectrum of its capabilities.

Destructure all weirdly-shaped objects from legacy APIs and praise ES8 🙂

PS: MDN now mentions the Invalid JavaScript identifier as a property name

--

--