Destructuring in ES6 | ES2015
Destructuring is the process of unpacking the array or object to a set of variables. The two types of destructuring are
- Array destructuring
- Object destructuring
Array Destructuring
You can destructure the individual elements in the array and assign them to individual variables in a single assignment instead of assigning each item of the array to a variable. [] square bracket is used for array destructuring. Please check the below code
let arr = ["Sridhar","Narasimhan"];
//destructuring will be like below if array destructuring is not used ES5 format
// firstName = arr[0];
// lastName = arr[1];
let [firstName, lastName] = arr;
console.log(firstName );
console.log(lastName );
https://codepen.io/Sridhar-Narasimhan/pen/KKgXZVw?editors=1111
Object Destructuring
Object destructuring allows to destructure the individual property of the object and assign it to an individual variable. {} curly brace is used for object destructuring. The variable name should be the same as the property name in the object. Please check the code below
let employee = {name:"Sridhar", email:"sridharn@xyz.com", role:"developer"};
// ES5 format
// let name = employee.name, email = employee.email, role = employee.role;
let {name,email,role} = employee;
console.log(`${name} is a ${role} and mail him @ ${email}`);
https://codepen.io/Sridhar-Narasimhan/pen/dypVJGm?editors=1111
Why destructuring - Destructuring helps in resolving 2 main problems
- Function with multiple parameters - The positional parameter in the function can be handled easily. In functions receiving more parameter. First, we need to remember or lookup which arguments go in which order. This can be handled by passing arguments as a single object and destructure it in the function arguments signature.
//ES5 code
let person = {
firstName: "Sridhar",
lastName : "Narasimhan",
role:"developer",
socialMedia:{
twitter: "https://twitter.com/dharsha007",
linkedIn:"https://www.linkedin.com/in/sridhar-narasimhan/"
}
}
function tweetUser(firstName, lastName, role ,socialMedia){
console.log("Tweet about " + role + " " + firstName + " " + lastName + " using " + socialMedia.twitter);
}
tweetUser(person.firstName, person.lastName, person.role, person.socialMedia);
https://codepen.io/Sridhar-Narasimhan/pen/WNGZdxe?editors=1111
//ES6 code
let person = {
firstName: "Sridhar",
lastName: "Narasimhan",
role: "developer",
socialMedia: {
twitter: "https://twitter.com/dharsha007",
linkedIn: "https://www.linkedin.com/in/sridhar-narasimhan/"
}
}
function tweetUser({ firstName, lastName, socialMedia }) {
console.log(` Tweet about ${firstName} ${lastName} using ${socialMedia.twitter}`);
}
tweetUser(person);
https://codepen.io/Sridhar-Narasimhan/pen/dypVJXm?editors=1111
- Function with parameters that needs default values - we need to read the documentation to know about arguments which we don’t care about i.e arguments receiving null values. The default value option helps to avoid passing null values or having undefined values in function arguments.
//ES5 code
let person = {
firstName: "Sridhar",
lastName: "Narasimhan",
role: "developer",
socialMedia: {
twitter: "https://twitter.com/dharsha007",
linkedIn: "https://www.linkedin.com/in/sridhar-narasimhan/"
}
}
function tweetUser(firstName, lastName, role, socialMedia) {
role = role || "Blogger"; //role default value is set if it value received is null
console.log("Tweet about " + role + " " + firstName + " " + lastName + " using " + socialMedia.twitter);
}
tweetUser(person.firstName, person.lastName, null, person.socialMedia);
https://codepen.io/Sridhar-Narasimhan/pen/BaLwJQe?editors=1111
//ES6 code
let person = {
firstName: "Sridhar",
lastName: "Narasimhan",
//role: "developer",
socialMedia: {
twitter: "https://twitter.com/dharsha007",
linkedIn: "https://www.linkedin.com/in/sridhar-narasimhan/"
}
}
//default value for role variable is set as Blogger using default params
function tweetUser({ firstName, lastName, role = "Blogger", socialMedia }) {
console.log(` Tweet about ${role} ${firstName} ${lastName} using ${socialMedia.twitter}`);
}
tweetUser(person);
https://codepen.io/Sridhar-Narasimhan/pen/YzGrYpj?editors=1111
Use cases
Combining arrays
We commonly combine arrays while coding and consider the use case of calendar usage, where workweek and weekend have a major role. We can combine both the workweek and weekend to get the whole week using the rest operator (… - triple dot). Let us see this in code as below
//considering india
const workWeek = ["monday","tuesday","wednesday","thursday","friday"];
const weekEnd = ["saturday","sunday"];
const week = [...workWeek, ...weekEnd];
console.log(week)
https://codepen.io/Sridhar-Narasimhan/pen/NWRaXbK?editors=1111
Swap variable
We usually have a temp variable to do the swapping of values in variables. But we can do this easily with swapped variables in a destructured array.
let x=10;
let y=20;
console.log(x,y);
[x,y] = [y,x]; //swap makes x = 20 and y =10
console.log(x,y);
https://codepen.io/Sridhar-Narasimhan/pen/ZEpXvpp?editors=1111
Immutable Operations
Destructuring helps to process immutable operations both in array and object. In react, we need to consider immutable object usage for handling unidirectional data flow. We will see the array and object example below
// Immutable operations in Array
const week = ["saturday","sunday","monday","tuesday","wednesday","thursday","friday"];
const [,, ...workWeek] = week;
console.log(workWeek);
console.log(week);
// Immutable operations in Object
let person = {
firstName: "Sridhar",
lastName: "Narasimhan",
role: "developer",
socialMedia: {
twitter: "https://twitter.com/dharsha007",
linkedIn: "https://www.linkedin.com/in/sridhar-narasimhan/"
}
}
let { firstName, lastName, ...rest} = person;
console.log(rest);
console.log(person);
https://codepen.io/Sridhar-Narasimhan/pen/dypVVzb?editors=1112
Browser support details
You can able see the support for destructuring in the browser using the below link caniuse.com/?search=destructuring
Summary
Destructuring is an awesome feature useful in many small cases. Hope you enjoyed this blog.