How does object destructuring extract properties into variables?
Quick answer
Object destructuring reads properties from an object into variables. By default, each variable has the same name as its property: const { id } = user. To use a different variable name, write const { name: displayName } = user. Add = value for a default; it applies when the property is missing or its value is undefined, but not when its value is null. [S1]
The question, the details, the next step.
A practical checklist
Start with the source object, such as
const { id } = user.Use the property name for a directly matching variable.
Write
propertyName: variableNameto give the variable another name.Add
= fallbackfor a missing orundefinedvalue.Remember that a default does not replace
null.Use
Object.hasOwn()separately if you need to distinguish an absent own property from one set toundefined.
A few more useful answers
Does destructuring with a default change the original object?
No. The pattern assigns the accessed value to a variable; it does not assign the fallback back to the source property.
Can destructuring read a property that the object inherits?
Yes. Property access during object destructuring follows the prototype chain, so an inherited property can be read. [S1]
Does a default distinguish an absent property from one set to `undefined`?
No. The same default is used in both cases. Check ownership separately if that difference matters. [S1]
Sources
References used for this guide.
- [S1] Destructuring — JavaScript | MDN developer.mozilla.org · Checked
