Modern JavaScript for React: Destructuring Objects & Arrays – Part 4

In modern Javascript, destructuring is a process of taking only part of data from given Objects and Arrays. Destructuring is heavily used in the ReactJs.

In this article, we will see how to use destructuring with real objects and arrays.

Let’s start,

Here is what you do when you want to store data from an object to the variable. It’s a traditional and simple way. See below code.

 
 const PI = Math.PI;
 const E = Math.E;
 

Now let’s see the destructuring way of above code.

 
 const {PI, E} = Math;
 

In the above code, you can see that we are fetching data from the Math object without accessing its properties directly. Whatever properties you have defined in the const automatically fetch and store the value of PI and from Math object.

How Destructuring is Useful in ReactJs

Let’s see ReactJs component example where destructuring is used. Here is the example of require component.

 
  // Destructuring used for require component to access its objects
  const {Component, Fragment, useState} = require('react');
  
  // This is how you can use useState hook
  useState();
 

To access useState() hook without destructuring you had to write extra lines of code. But, as shown in the above example, you could see you are able to access useState() hook directly from require component without any extra effort or code.

Destructuring Props in ReactJs

Destructuring is very useful when you use it for Props (Arguments passed to the function). Let’s see how to use it with the props. Let’s look at the code below.

 
  const { PI, E } = Math;

  const circle = {
   lable: 'circleX',
   radius: 2,
  };

  const circleArea = ({radius}) =>
     (PI * radius * radius).toFixed(2);

  console.log(
   circleArea(circle)
  );
 

In the console.log we are calling the circleArea function and passing circle object as props.

But, if you notice carefully in the circleArea function we are not accepting circle object. Instead, we have defined {radius} property of circle object.

CircleArea function only requires a value of radius. It doesn’t need circle object inside as far as current functionality concerned.

Note: You might get the concern that ‘we could have passed circle.radius instead passing circle object (without using destructuring)?’

Valid Question! But, think for a movement, what if we need additional properties from circle object when we add more logic to the CircleArea function? So, that’s why it is very useful to use destructuring when you are using props.

Benefits of Destructuring

Now, we will look at more examples where destructuring is very beneficial.

Multiple Arguments in Destructuring

In the above code example, if we want to set a default value for toFixed() method using argument then destructuring also allows doing that. See below example.

 
  const circle = {
    lable: 'circleX',
    radius: 2,
   };

  // Here we have passed value as argument for toFixed()   
  const circleArea = ({radius}, {precision}) =>
     (PI * radius * radius).toFixed(precision);
 

Default Value in Destructuring

You can also set a default value to the argument as shown in the below code. You can see we have set precision value default to 2.

 
  const circleArea = ({ radius }, { precision = 2 }) => {
       return (PI * radius * radius).toFixed(precision);
  };
 

Optional Parameter in Destructuring

Suppose you want to make a precision argument optional than you have to add ={} after the closing of a precision parameter. See the below code.

 
   const circleArea = ({ radius }, { precision = 2 } = {}) => {
       return (PI * radius * radius).toFixed(precision);
   };
 

Working Example of Destructuring Parameters

    
   const { PI, E } = Math;

   const circle = {
            lable: 'circleX',
            radius: 2,
   };
   
   const circleArea = ({ radius }, { precision = 2 } = {}) => {
      return (PI * radius * radius).toFixed(precision);
   };

   console.log(circleArea(circle, { precision: 5 }));
  

In console.log we are passing precision parameter also. Which will override the default value 2. The output of the above code: 12.56637

Destructuring with Arrays

To extract only some values, destructuring is very useful in arrays. Let’s see the example.

 
  const [first, second,, forth] = [10, 20, 30, 40];
 

In the above code, only 10, 20 and 40 will get stored inside first, second and fourth respectively. Value 30 will get skiped and to skip that we have left 3rd place blank (,,).

Array Destructuring ReactJs Example

This is how array destructuring used in ReactJs for useState Hook.

 
  const [value, setValue] = useState(initialValue);
 

Rest Parameter Destructuring

What if you want to separate some values from the array and remaining store into another array? You can use rest (…) operator to make this possible. Let’s see the example.

 
  const [first, ...rest] = ['Broccoli', 'Apple', 'Mango', 'Banana'];
 

Suppose, you want to separate Broccoli from the Array list. Use separate const to hold first andoperator (…) to hold remaining values. If you see values of first and …rest in console window then you will see variable first is holding Broccoli and …rest will be holding an array of AppleMango and Banana.

Filter Out Properties from Object Using Destructuring

You can also filter out properties from an object as you do for an Array. Let’s see the example.

 
  const data = {
    val1: '100',
    val2: '200',
    firstName: 'Tutorial',
    lastName: 'Funda',
  };

  const {val1, val2, ...personal} = data;
 

val1 and val2 respectively hold 100 and 200 and …personal array will hold firstName and lastName values.

Hope you have understood destructuring in modern JavaScript well enough. In the upcoming posts, we will explorer the next topic about modern JavaScript for ReactJs.


Subscribe Now!

Subscribe Us For Latest Articles