JavaScript·100 questions

QUESTION: What is destructuring?

Answer

Destructuring in JavaScript is a convenient syntactic sugar that allows extracting data from arrays and objects and assigning them to variables in a shorter and more expressive way. This approach significantly reduces the amount of boilerplate code.

When working with arrays, destructuring allows assigning new variables to elements based on their strict order of appearance. For example, a construct like const [a, b] extracts the first two elements of the array into the corresponding constants.

For objects, matching occurs not by order, but by exact key names. A notation like const {name, age} automatically extracts the name and age properties from a given user object regardless of their location in the original structure.

If an existing key name is not suitable for the current context or conflicts with already declared variables, the language allows renaming the variable right during destructuring. A colon is used for this, for example, when extracting the name key into a new variable n.

Additional flexibility is provided by default values, which can be set in case a property is missing. They can be specified by writing an equal sign and the desired value directly inside the destructuring pattern.

Declare a variable using curly or square brackets on the left side of the expression.
Specify the names of the extracted object properties or array element positions.
Assign the target object or array to the right side of the expression for unpacking.
Add a colon and a new variable name to rename the property if necessary.

In addition, deep or nested destructuring is supported. It allows reaching properties of internal objects with a single line of code, extracting a property from a nested object using a combination of a colon and curly braces.

Was this answer helpful?

More questions in this topic

Related questions from other topics