Open In App

What is a Destructuring assignment and explain it in brief in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

The Destructuring assignment is the important technique introduced in ECMAScript 2015 (ES6) version of JavaScript that provides a shorthand syntax to extract or unpack array elements or properties of an object into distinct variables using a single line of code. In other words, this assignment helps us to segregate data of any iterable as well as non-iterable object and then helps us to use that segregated data individually on need or demand. It makes the code shorter and more readable.

Let us have a look over the below mentioned syntax of Destructuring assignment which will help us to reduce our code and make it more readable and scalable too. 

Syntax: The left-hand side of the expression of Destructuring assignment contains the distinct variables which actually defines what properties/values are to be unpacked or segregated from the source variable (or an array or an object) and the right-hand side specifies the corresponding object or array to which we are about to extract our data (the source variable which could be any iterable or non-iterable object). 

// array destructuring
[variable1, variable2, .... , variableN] = array_variable;

// object destructuring
{property1, property2, .... , propertyN} = object_variable;

Example 1: The following example showcases the usage of extracting required array elements into distinct variables using Array Destructuring and will also help you to understand how Destructuring can be used to write clean and concise code.

Javascript




<script>
//array destructuring
let rainbow = ["Violet", "Indigo", "Blue", "Green",
               "Yellow", "Orange","Red"];
let [V,I,B] = rainbow;
console.log(V,I,B);
</script>


Output:

Violet Indigo Blue

Example 2: The spread operator is also used to unpack array elements but the main difference between Array Destructuring and spread operator is that spread unpacks all the array elements and this spread operator doesn’t allow us to skip or choose elements according to our requirement. Using Array Destructuring, we can skip the elements which are not required by using a ‘comma separator.’

Javascript




<script>
let rainbow = ["Violet", "Indigo", "Blue",
    "Green", "Yellow", "Orange","Red"];
 
// Skipping alternate colors from the rainbow array
let [V,,B,,Y,,R] = rainbow;
 
// Violet Blue Yellow Red
console.log(V,B,Y,R);


Output:

Violet Blue Yellow Red

Example 3: In the following example, an address object is de-structured to obtain only the city and sector properties and display the output on the console. 

Object Destructuring is an important feature of JavaScript and is very useful when only certain properties of an object are to be used and the complete object is not required or  not in consideration. This feature of ES6 is commonly used in JavaScript frameworks and its main application is parameter de-structuring i.e. objects passed into function parameters can be de-structured before use, according to the function requirement.

Javascript




<script>
// Object destructuring
let address = { state: 'Punjab', city: 'Mohali', sector: 61 };
 
// Assign the address object directly as well
let {city, sector} = address;
console.log("City: " + city + ", Sector: " + sector);
 
// city = address.city
// sector = address.sector
</script>


Output:

City: Mohali, Sector: 61

Note: The order of name doesn’t matter in case we are implementing Object Destructuring in JavaScript.

For example, in the above illustrated example, if we change the order of names in which the particular object’s properties has been de-structured from the source object, then also our task will be same and result would also be the same. Let us see the implementation of this illustrated fact below (with the help of following code snippet):

Javascript




let address = { state: "Punjab", city: "Mohali", sector: 61 };
 
let { city, state, sector } = address;
 
console.log(
  `An employee lives in the state of ${state} and his city name is ${city}`
);
 
// This code is contributed by Aman Singla...


Output:

An employee lives in the state of Punjab and his city name is Mohali

Example 4: Object properties can also be extracted using a different variable name (an alias) other than the property name defined in the source object. The following example uses aliases to extract the values of state and city properties from the address object.

Javascript




<script>
// Using an alias for extracting object properties
let address = { state: 'Punjab', city: 'Mohali', sector: 61 };
let {state: stateName, city: cityName, sector} = address;   
console.log("State: " + stateName + ", City: "
    + cityName + ", Sector: " + sector);   
// stateName ->  alias for address.state
// cityName  ->  alias for address.city
</script>


Output:

State: Punjab, City: Mohali, Sector: 61

Example 5: A nested object i.e. an object within the source object can also be de-structured using the same syntax of Object Destructuring to access only the properties required. The example below contains an address object having a nested object pin which is de-structured to extract only the pin-code of the address.

Javascript




<script>
// Nested object destructuring
let address = {
    state: 'Punjab',
    city: 'Mohali',
    pin: {sector: 61, pincode: '160062'}
};
 
// Accessing only the 'pincode' property
// from address.pin (nested object)
//pincode = address.pin.pincode
let { state, city, pin: {pincode} } = address;
console.log("State: " + state + ", City: "
    + city + ", Pincode: " + pincode);
</script>


Output:

State: Punjab, City: Mohali, Pincode: 160062

Example-6: In this example we will try to understand how actually setting function parameter’s default value task works. In other words using the below mentioned code snippet we will try to understand how we may set a function parameter’s default value.

Javascript




let drawing_begins = ({
  size = "BIG",
  coordinates = { x: 0, y: 0 },
  radius = 25,
}) => {
  console.log(
    `Th drawing made so far is of the ${size} size, having the coordinates of (${coordinates.x} , ${coordinates.y}) and with the radius value of ${radius}`
  );
};
 
drawing_begins({
  coordinates: { x: 18, y: 30 },
  radius: 30,
});
 
// This code is contributed by Aman Singla...


Output:

Th drawing made so far is of the BIG size, having the coordinates of (18 , 30) and with the radius value of 30


Last Updated : 12 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads