Destructuring Objects And Arrays In ES6

Destructuring Objects and Arrays in ES6

 
In this article, we will learn about destructuring objects and arrays in ES6. We will also have a look into the JavaScript REST operator. 
 
So, let's give it a go. To follow along with the code snippets, you can use an online editor. One of the interesting new features introduced in ES6 is destructuring. It provides a way to break up objects and arrays into variables using a very concise syntax. Let's take a look into the below-given code snippet
  1. const studentDetails = {      
  2.    name : 'Joey',      
  3.    age : 26,      
  4.    country : 'USA'      
  5. }     
We have a Student Details object, and if we want to access the studentDetails.Name property. We need to write code like this.
  1. console.log(studentDetails.name);   
What if we want to use this property often in our code? Then we should keep it in a variable instead of using the studentDetails object every time.
  1. const name = studentDetails.name;      
  2. console.log(name);      
Now, our code can be a bit shorter every time we use the variable name, but we still have to manually write the code to declare the variables and extract the properties.
 
Destructuring provides an incisive way to break out an object's properties into separate parts. Let's see in practice
  1. const {name} = studentDetails;   
ES6 will declare a constant called "name" and assign the value of the studentDetails.name to it.
 
If we want to extract more properties of studentDetails, then we can just provide them and set the curly braces separated by commas, name, age, and country.
  1. const {name,age,country} = studentDetails;        
  2. console.log(name + ' '+age + ' '+country);  // will print Joey 26 USA   
We can also provide alias name to variable while extracting an object's property.
  1. const {name: StudentName,age : StudentAge, country : StudentCountry} = studentDetails;    
  2. console.log(StudentName + ' '+StudentAge);   
As you can see we have added alias name after the colon character. Beware though that since it uses a colon this looks a bit like a TypeScript type declaration. Inside a destructuring block, the colon has a different meaning, and it's only used to alias property names.
 
Let's take another example with undefined properties and passing default values to them,
  1. const studentDetails = {    
  2.    name : 'Joey',    
  3.    age : undefined,    
  4.    country : 'USA'    
  5. }   
As you can see, we on purpose declared age property as undefined to see the default value for destructing. If you'd prefer a value like 30 if age is undefined then we need to write code like this 
  1. const {name: StudentName,age : StudentAge = 30, country : StudentCountry} = studentDetails;   
When using destructuring, default values are only applied if the property is undefined, null will stay as null. As you can see we have assigned a default value for age to 30.
 

ES6 destructing works with more than just objects, it works with arrays too

 
Let's have some fun destructuring with Arrays using a new JavaScript operator rest.
 
Let's say we have an array of Student Names like Monika, Charlie, and Sheldon. If we want to assign the first name in this array to a variable called firstStudentName, then we can type in a traditional way.
  1. const studentNames = ["Monika""Charlie""Sheldon"];    
  2. const firstStudentName = names[0];   
Now let's see how we can use destructuring instead.
 
As you remember from earlier examples with objects, that when we were destructuring objects, we surrounded our destructuring assignment with curly braces. Curly braces are often used with objects in JavaScript.
 
The characters most often used with arrays are square brackets, and we use those to destructure an array.
  1. const [firstStudentName] = names;        
  2. console.log("Student name is "+firstStudentName);   // will print    
  3. const [firstStudentName, secondStudentName ] = names;        
  4. console.log("First Student name is "+firstStudentName);  // will print Monika    
  5. console.log("Second Student name is "+secondStudentName);  // will print Charlie    
What happens if the array's empty? JavaScript doesn't give an out of bounds error when using an array index that doesn't exist, it just returns undefined.
  1. const studentNames = [];    
  2. const firstStudentName = names[0]; //will be set to undefined using traditional way  
  3. const [firstStudentName ]= names; //will be set to undefined using destructuring 
The best thing about destructuring is that just like with objects it lets us easily supply a default value.
  1. const studentNames = [];    
  2. const [firstStudentName = "Joey" ] = names; //will be set to Joey   
If we are destructuring an array that has more elements than are pulled out in our assignment statement, it's possible to add one more variable to act as a placeholder for the remainder. The way you identify that, is with a triple dot which is also known as rest operator.  
  1. const studentNames = ["Monika""Charlie""Sheldon""Penny","Raj""Chandler"];    
  2. const [firstStudentName, secondStudentName, ...otherStudents ] = names;  // we are using rest operator with otherStudents  
  3. console.log(firstStudentName); // will print Monika    
  4. console.log(secondStudentName); // will print Charlie    
  5. console.log(otherStudents); // will print ["Sheldon", "Penny", "Raj", "Chandler"]   
Having a rest item is optional, but if we have one it has to be the last item in the list. If there aren't enough elements in the array being destructured to reach the rest item, the designated variable will get assigned an empty array, not null or undefined. 
  1. const studentNames = ["Monika""Charlie"];    
  2. const [firstStudentName, secondStudentName, ...otherStudents ] = studentNames;    
  3. console.log(firstStudentName); // will print Monika    
  4. console.log(secondStudentName); // will print Charlie    
  5. console.log(otherStudents); // will print []   
The rest operator isn't just for destructuring, we can use it when declaring a function that takes many parameters. Let's create a function that will say hello to any number of students that we pass in by name.
  1. sayHello("Joey","Chandler","Ross");    
  2. function sayHello(...studentNames: string[]){    
  3.    studentNames.forEach(student => console.log("Hello, "+student))    
  4. }   

Summary

 
I also used a handy function available on arrays in ES5 and higher, forEach, which lets us define a function that'll be called for each element in the array. I should note that forEach isn't available by default in ES3 environments like IE8 and lower, but it can be poly-filled, or you could just write a for loop here instead.


Similar Articles