Do we have to always use {} when creating a variable through destructuring?


#1

Question

Do we have to always use {} when creating a variable through destructuring?

Answer

If we are implementing adestructuring assignment on an object, yes!
Because by saying something like:
const { name } = obj;
We are not just creating a variable name, we are pulling the property name from obj and turning it into a variable that holds the same value the property itself had in the object, let’s expand more into that example:

const obj = {
  name: 'Mr. Obj',
  pastTime: 'Volley Ball',
  yearsTraining: [ 1992, 1993, 1994, 1995, 1996],
}

Now when we usually wanted to get the name, we would simply say obj.name, if we wanted to store it in a variable we would do:
const name = obj.name;
or
const objName = obj.name;

then console logging objName will give us Mr. Obj, we do the same with destructuring, it just makes it a little easier, because you can also do several values at a time, and we use the {} curly braces to let JavaScript know that those are properties of the object. Like so:

const { name, pastTime, yearsTraining } = obj;

We do need to be careful with naming when using destructuring. The variable name needs to be exactly the same as the property name in the object because how JavaScript reads it, is like pulling values from the object, so it will search for the name within the object and assign it as a variable with its value. an example is if you try this:

const { foo } = obj;

console.log(foo) // will print undefined because the object does not have a key foo

In short, use {} when destructuring an object, and always use the property names for the variable names.