Destructuring and Spread Operator

1 Min. Read
Oct 15, 2019

Object Destructuring

Object Destructuring is one of the features of the javascript which is used to extract the values of the properties and store in the separate variable. It helps to minimize the length of the code. For e.g.

1
2
3
4
5
6
7
8
    const address = {
        street: 'a',
        city: 'b',
        country:'c'
    };
    const street = address.street;
    const city = address.city;
    const country = address.country;

In above code, the “address.” is repeated for storing the street,city, and address property of the object to the respective variables. This redundancy can be avoided with the help of object destructuring.

1
    const {street, city, country} = address ;

We can also use an alias to denote the different name for the variable.For e.g

1
    const {street: st} = address;

Here,we defined new constant called “st”, and we set it to street property of the address object.

Spread operator

Spread operator is denoted by using the “…” symbol. It is used to clone an array/object, concatenate the arrays, add new item to the concatenated array. For e.g.

1
2
    const first = [1,2,3];
    const second = [4,5,6];

cloning an array:

The array can be cloned as following:

1
    const clone = [...first];

concatinating the two arrays:

The array can be concatenated as following:

1
  const combined = [...first, ...second];

addding new item to the concatenated array:

New element can be inserted into the concatenated arrays as following:

1
    const combined = [...first, 'middle', ...second];

cloning an object

The object can be cloned as following:

1
2
3
4
    const firstObj = {name:'ram'};
    const secondObj = {address:'nepal'}

    const cloneObj = [...firstObj];