Confusing Destructing Nested Objects Syntax

Destructuring assignment to assign variables from nested objects example:

const a = {
  start: { x: 5, y: 6},
  end: { x: 6, y: -9 }
const { start : { x: startX, y: startY }} = a;

The syntax in the last line is confusing to me because first we’ve to destruct the object a using {} brackets to access its value. Then we’ve to access the value of the properties inside start, which itself is an object, to get the values of x and y. Here we don’t use the same syntax like, {x: startX, y:startY} = a.start. Is it always like this for nested objects or am I missing something?

if you have multiple objects nested, in this way you still need only one line instead of one line for each nested object, so you use nested destructuring

Yea, but the syntax is not consistent now, is it?

why do you think it is not?
instead of doing

const {start : nestedObject}= a;
const {x : startX, y : startY} = nestedObject;

you make it in one line, substituting {x : startX, y : startY} in place of nestedObject in the first line

Yea, but we didn’t use the equal sign anymore. Like, const { {x : startX, y : startY} = start} = a;

that’s wrong syntax

inside destructuring you use : to say “put the value of what’s to the left of it, in what is to the right of it”

so when you do {start : ...} you are taking the value of the property start and putting it to the right of it. that’s already the value of the property start, so you don’t need any extra syntax to do destructuring with that value

I understand, but the value of the start is itself an object, right? Don’t we have to destruct that first?

we are destructuring the nested object with {x : startX, y : startY}

this is doing the thing in two lines:

doing it one line, instead of storing the value of start in nestedObject, we do destructuring in place

total it is “take the property x in the property start from the object a and store its value in variable startX

This pattern

{ start: { x: startX, y: startY }}

Matches this:

{ start: { x: 5, y: 6 }}

I’m not quite sure your thinking as to what the inconsistentcy is here. You are accessing a.start.x and a.start.y.

However, I get that it is confusing to read. Ideally, destructuring nested objects it not something you want to be doing very often because it can get very hard to read very fast.

1 Like

Ah, in-place destruction. That’s where I missed it. Otherwise, the syntax didn’t make sense because putting the value of what’s to the left of : which is an object itself, in what’s to the right which is also the same.