Destructuring in Javascript

When working with arrays and objects, often we don't need to access all the values but rather only some of the values in arrays or objects. For example, we might need to access only the first three elements of an array or only two properties of an object.

What is Destructuring in Javascript?

Destructuring in Javascript is used in such scenarios and is used to unpack values and assign them to different variables. This makes assigning values from arrays and objects easier. For example, if we have an array defined.

const languages = ["c#","java"];

then we can use destructuring for assigning values to variables lang1 and lang2.

[lang1,lang2]=  languages

Now the variable lang1 should have a value of "c#" and lang2 should have a value of "java" if we execute the below code.

const languages = ["c#","java"];
[lang1,lang2]=  languages
console.log(lang1,lang2)

Then we would get the output.

c# java

As you can see, this simplifies assigning values from array elements to different variables so much easier.

Similarly, we can use Destrucuring in Javascript to assign values from objects to variables.

For example, if we define an object.

const userObj = { name:"ashish", language:"c#" };

then we can use object destructuring to assign values to name and language variables.

const {name,language}=userObj;

Now if we log the values of the variables' name and language.

console.log(name,language)

then we would see the following output.

ashish c#

Default values

When assigning values using destructuring we can assign default values to the variables. These default values will be used if the array does not contain a value for assigning. For example, in the following assignment.

[a = 0, b = 1] = [100,200];

a and b will have the values 100 and 200, but if the assigned values are missing, then these will have values 0 and 1.