VOOZH about

URL: https://www.geeksforgeeks.org/javascript/destructuring-assignment-in-javascript/

⇱ Destructuring in JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Destructuring in JavaScript

Last Updated : 9 Nov, 2024

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 Destructuring

Array members can be unpacked into different variables. The following are different examples.


Output
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. 


Output
a
[ 'c', 'd' ]

Example of Swapping : Values can be swapped using destructuring assignment as below: 


Output
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. 


Output
a
b

Example 6: In ES5 to assign variables from objects its implementation is 


Output
21
-34
47

Object destructuring

Simple Object destructuring : In the below examplex, properties (and their values) of an object are assigned to variables.


Output
10
20

Output
10
20
{ m: 30, n: 40 }

Nesyed Object destructuring : The Nested objects can also be destructured using destructuring syntax. 


Output
15 16

Output
GFG
India
JS
destructuring
Comment