Transcript from the "Object Assignment Destructuring" Lesson
>> Kyle Simpson: Okay, so exactly like with array destructuring, if the target that we're assigning to in one of these destructurings is already an existing location, like an existing variable, then we don't need to keep the declarations on. So for example, if I already had var first and second having been created somewhere, then I don't need the vars on those to be included.
[00:00:27] The same is gonna be true over here, if I have a var first and a var second, I guess we can take off the third now. If I've a var first and a var second that all ready exists, then I don't need a declaration here to assign to it.
[00:01:02] So this will end up throwing a syntax error because that's not valid syntax for a block. And so, unfortunately because of our history of having our, overloading of curly braces, meaning like fifteen different things, they had to come up with some sort of way to distinguish. That this is a destructuring pattern and not a block.
[00:01:25] And the choice that they made is both good and bad. So here's how you disambiguate a destructuring pattern that has no declarator. You have to wrap the entire thing in a parenthesis. Not just the pattern itself but the whole statement has to be wrapped in a parenthesis. That's how you disambiguate that this is a destructuring pattern instead of a block.
>> Kyle Simpson: Remember you don't need those parenthesis if there is anything else in front of it, including a declarator. Or, you recall that we talked earlier with arrays. That sometimes you wanna have a reference to the object, in this case, as well. So in the case where I wanna grab a reference to the thing as well as to the destructure it, I could say temp equals, and now I don't need the parenthesis.
[00:02:28] Because this curly brace is no longer in a position where it could be confused with a block.
>> Kyle Simpson: So for that reason alone, if I'm going to both destructure and also capture the whole value, I actually do prefer to do it in this order. I prefer to list the first variable being the one that captures the whole thing.
[00:02:57] And then in the chain of assignment have the destructuring pattern. And it's because in the object case it makes it nicer to not need to use the parenthesis around it. I will say that it is not all that common that I need to do a destructuring of objects that I don't need to declare.
[00:03:19] It's rare that I'm destructuring to things that already exist but when it does happen it's a little annoying to have to remember the parenthesis. And in those cases if I need the variable anyway, just use it and then you don't need to worry about the parenthesis.