Javascript – Destructuring

OVERVIEW

Destructuring is a feature which allows us to unpack values from arrays or properties from objects without having to write statements for them. In the sample code in lines 5,6 , we have an example of using destructuring to use the items in the string array. Each element is given a name. You can skip certain elements also by using empty value in its places as shown in lines 8,9.

A third way is to access only some values and then get the rest of the values in a single variable. This is done by prefixing the variable name with three dots as shown in lines 11,12.

You can actually do away with the variable name of the array itself and directly assign names to values as shown in line 15.

Using destructure syntax , we can swap values as shown in lines 17,18 and then 26,27,28.

We can use the same destructuring concept for properties in Objects as shown in lines 30 onwards. However, you cannot skip values like you could do in arrays.

SAMPLE CODE

<html>
	<head><title>Destructuring</title>
	
	<script>
	   let arr = ["This", "is", "a", "test", "string"];
	   let [a1, a2, a3, a4,	a5] = arr;

	   let arr2 = [56,4,34,12];
	   let [n1,,,n4] = arr2;

	   let arr3 = [156,14,134,12];
	   let [m1,...mall] = arr3;


	   let [fname, lname] = ["Tom", "Thumb"];

	   let x = 190;
	   let y = 900;

	   document.write(arr[0] + "," + arr[1] + "<br>");
	   document.write(a1 +"," + a2 + "," + a5 + "<br>"); 
	   document.write(n1 +"," + n4 + "<br>");
	   document.write(m1 +"," + mall + "<br>");
	   document.write(fname +"," + lname + "<br>");

	   document.write(x +"," + y + "<br>");
	   [x,y] = [y,x];
	   document.write(x +"," + y + "<br>");

	   let Person = {id:788, name: "jim Logan", age:44};
	   let	{id, name, age} = Person;

	   let Person2 = {id2:788, name2: "jim Logan", age2:44};
	   let	{age2} = Person2;


	</script>
	
	</head>
	<body>
	</body>
</html>

The output is shown below

This,is
 This,is,string
 56,12
 156,14,134,12
 Tom,Thumb
 190,900
 900,190

Be the first to comment

Leave a Reply

Your email address will not be published.


*