Tuesday, 25 December, 2018 UTC


Destructuring in JavaScript can initially feel confusing but the truth is that destructuring can make your code a bit more logical and straight forward. Destructuring does look a bit more complex when you’re looking for a property several objects deep, so let’s have a look at how to do that!
Simple destructuring looks as follows:
const { target } = event;
Here we use {} and = to name a variable the same as the property name (you can also use an alias while destructuring!). Grabbing a nested object value is a bit more complicated, however:
// Object for testing
const x = { y: { z: { a: 1, b: 2} } }

// Get "b"
const { y: { z: { b } } } = x;

console.log(b); // 2
console.log(z); // z is not defined
console.log(y); // y is not defined
Here we an object-like syntax with {} and : to set a var based on the nested obect property. Note that only the last nested property is given as a variable; the parents we reference along the way do not.
Destructuring can take a while to get used to but, the more I use it, the more I appreciate how simple my code can be: no “dot” hell and less overall code!
The post Nested Destructuring appeared first on David Walsh Blog.