![]() |
VOOZH | about |
Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables.
Array members can be unpacked into different variables. The following are different examples.
Example 1 10 20 30 40 Example 2 10 20 40 Example 3 10 20
Example with Rest Operator : In order to assign some array elements to variable and rest of the array elements to only a single variable can be achieved by using rest operator (...) as in below implementation. But one limitation of rest operator is that it works correctly only with the last elements implying a subarray cannot be obtained leaving the last element in the array.
a [ 'c', 'd' ]
Example of Swapping : Values can be swapped using destructuring assignment as below:
20 10
Example of Function Return: Data can also be extracted from an array returned from a function. One advantage of using a destructuring assignment is that there is no need to manipulate an entire object in a function but just the fields that are required can be copied inside the function.
a b
Example 6: In ES5 to assign variables from objects its implementation is
21 -34 47
Simple Object destructuring : In the below examplex, properties (and their values) of an object are assigned to variables.
10 20
10
20
{ m: 30, n: 40 }
Nesyed Object destructuring : The Nested objects can also be destructured using destructuring syntax.
15 16
GFG India JS destructuring