what is destructuring in javascript

11 months ago 39
Nature

Destructuring is a feature in JavaScript that allows unpacking values from arrays or properties from objects into distinct variables. It is a shorthand syntax that makes it easier to extract only what is needed from an array or object.

In array destructuring, the syntax uses square brackets on the left-hand side of the assignment to define what values to unpack from the sourced array. For example, const unpacks the first two values of the array into variables y and z.

In object destructuring, the syntax uses curly braces on the left-hand side of the assignment to define what properties to unpack from the sourced object. For example, const { a, b } = { a: 1, b: 2 } unpacks the properties a and b of the object into variables a and b.

Destructuring can also be used with function parameters to unpack objects passed into the function. The destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Computed property names, like on object literals, can be used with destructuring. Additionally, arrays can be used with objects in object destructuring. Objects can also be nested when destructuring.