Safer Code with ES6 Destructuring — Explained in One Example

Esbjörn Blomquist
2 min readOct 30, 2019

--

Uncaught TypeError: Cannot read property ‘x’ of undefined

Recognize this? Seen this before? It is perhaps the most common error in Javascript.

Error prone dynamic data

We often deal with dynamic data in complex structures in all web applications (browser + node.js) which, when we try to use that data, might produce unexpected behaviors and errors.

Let’s look at a small example where we have a collection items (key indexed) of objects with certain properties. We need to get hold of an item's parent, and some properties from that parent item. It could look like this:

But this is a whole bunch of delicious baits for the unforgiving X-of-undefined-creature. It will jump out, attack you from the side, and bite you — hard!

The problem is that we expect item to have a parent and that this parent id exists in items and that the parent item has both types and name defined. types might also cause problems further ahead if it is assumed to be an array.

Fallback default values to the rescue?

We have to insert multiple fallback default values, perhaps like this:

Ok, so we can feel rather safe now perhaps? But it looks a bit messy and unstructured, doesn’t it?

ES6 Destructuring

Let’s start over completely and try the amazing ES6 Destructuring syntax:

We first destructure item and also rename its parent property to parentId (because we can, otherwise it would automatically get the nameparent).

Then we find the parent in items by destructuring that whole collection, and at the same time we also destructure the parent to reach into it and get both types and name, with fallback defaults.

Conclusion

If we…

Use destructuring as much as possible:

  • Whenever we need something from within an object or array
  • Use eslint to get warnings and help

Try to always think about default values in our destructurings:

  • Much in the same way that we are used to with function arguments

…we might then be able to better shield ourselves against X-of-undefined errors.

A big bonus: Half the code size!

--

--

Esbjörn Blomquist
Esbjörn Blomquist

Written by Esbjörn Blomquist

Software architect and developer with web and functional JavaScript close to his heart. Worked many years with web solutions mainly within the IoT field.