Modern JavaScript has many new features that make it easy to write code in a simple and structured manner.

One of the handy modern features available in ES6+ is array and object destructuring.

JavaScript frameworks like React.js and Angular encourage the use of this technique.

Laptop on a desk showing a code editor with a dark background.

So its essential to understand what destructuring is all about and how to use it while writing code.

What Is Object and Array Destructuring in JavaScript?

Destructuring in JavaScript refers to the process of unpacking values from an array or object.

It’s also helpful when processing returning values from a complex function or expression.

This concept is one of thebest practices you should follow while writing React code.

This is the fundamental concept behind destructuring.

Remember that if your array contains more items than you’re unpacking, JavaScript will ignore the extra items.

JavaScript’s destructuring pattern also allows you to skip certain elements by using an empty comma.

The code above uses the empty space to ignore value2in the arrayarr.

Instead of assigning value2to variablec, it skips to the next item in the array.

It also ignores the fourth value because it doesn’t specify a variable to store it in.

Variablebkeeps its default because a value is not provided.

How to Destructure Objects

Destructuring objects is not so different from arrays.

However, you don’t have to use the exact property names in the object.

And like arrays, destructuring a property name that doesn’t exist will beundefined.

Otherwise, JavaScript will throw an exception.

Using destructuring, you’re able to quickly unpack values from arrays and objects.

Destructuring can also prove handy in other situations, like swapping values of two variables.