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
- const studentDetails = {
- name : 'Joey',
- age : 26,
- country : 'USA'
- }
We have a Student Details object, and if we want to access the studentDetails.Name property. We need to write code like this.
- 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.
- const name = studentDetails.name;
- 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
- 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.
- const {name,age,country} = studentDetails;
- console.log(name + ' '+age + ' '+country);
We can also provide alias name to variable while extracting an object's property.
- const {name: StudentName,age : StudentAge, country : StudentCountry} = studentDetails;
- 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,
- const studentDetails = {
- name : 'Joey',
- age : undefined,
- country : 'USA'
- }
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
- 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.
- const studentNames = ["Monika", "Charlie", "Sheldon"];
- 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.
- const [firstStudentName] = names;
- console.log("Student name is "+firstStudentName);
- const [firstStudentName, secondStudentName ] = names;
- console.log("First Student name is "+firstStudentName);
- console.log("Second Student name is "+secondStudentName);
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.
- const studentNames = [];
- const firstStudentName = names[0];
- const [firstStudentName ]= names;
The best thing about destructuring is that just like with objects it lets us easily supply a default value.
- const studentNames = [];
- const [firstStudentName = "Joey" ] = names;
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.
- const studentNames = ["Monika", "Charlie", "Sheldon", "Penny","Raj", "Chandler"];
- const [firstStudentName, secondStudentName, ...otherStudents ] = names;
- console.log(firstStudentName);
- console.log(secondStudentName);
- console.log(otherStudents);
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.
- const studentNames = ["Monika", "Charlie"];
- const [firstStudentName, secondStudentName, ...otherStudents ] = studentNames;
- console.log(firstStudentName);
- console.log(secondStudentName);
- console.log(otherStudents);
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.
- sayHello("Joey","Chandler","Ross");
- function sayHello(...studentNames: string[]){
- studentNames.forEach(student => console.log("Hello, "+student))
- }
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.