Power of Destructuring of Object in JavaScript

We use most of the time object or array in our day to day JavaScript programming. Both help to create a single entity like a packet of items.

But many times we want to unpack the packet of items. This can be done in a various way but the Destructuring feature of JavaScript is handy to achieve this.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

MDN Definition

Let Start with Array destructuring.

Array destructuring:

let [var1,var2,...] = array
let numArray = [1,2,3,4,5,6];
let one = numArray[0];
let two = numArray[1];
console.log(one,two) // 1 2
// ....
//Better way with Destructuring
let [one, two, three] = numArray
console.log(one,two,three) // 1 2 3

1. Skip/Ignore Value:

Suppose we have an array with ten values but we want first and third number then

let numArray = [1,2,3,4,5,6,8,9,10];
let [a,,b] = numArray
console.log(a,b) // 1 2

If we want to skip/ignore any return values we can simply specify blank as we did in the above example.

Some other example

let arr = [1,2,[5,55,555],6,7] // nested array
let [a,b,[c,d,e],f,g] = arr;
console.log(a,b,c,d,e,f,g) //1 2 5 55 555 6 7

2. Default value:

A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

let a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7

We can use it with any iterable.

let [a,b,c] = "singhak"
console.log(a,b,c) //s i n'

let name = "Anil Singh"
let [a,b] = name.split(" ") 
console.log(a,b) // Anil Singh

3. Rest Pattern:

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

const [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]

Always consider using rest operator as the last element.

const [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
// Always consider using rest operator as the last element.

4. Swapping Variable:

let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

It’s always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

function f() {
  return [1, 2];
}

let a, b; 
[a, b] = f(); 
console.log(a); // 1
console.log(b); // 2

5. Object destructuring:

{prop1,prop2,...,propn} = object
const user = {
    fstName: "Singhak,
    lstName: ".in"
};

const {fstName, lstName} = user;

console.log(fstName); // "Singhak"
console.log(lstName); // ".in" 

The statement const {fstName, lstName} = user defines the variable fstNameand lstName and initializes it with the value of user.fstName and user.lstName property.

6. Default Value:

const { prop = defaultValue } = object;

In many cases, we want to assign a default value to a variable, in the case that the value unpacked from the object is undefined.

const {a = 10, b = 5} = {a: 3};

console.log(a); // 3
console.log(b); // 5

In the above example, there is no property “b” in the given object then the default value will be assign.

const {a = 10, b = 5} = {a: 3, b:null};

console.log(a); // 3
console.log(b); // null

If the property is available in the given object then the value of the property will be assigned even the value is null or undefined

7. An assignment without declaration:

A variable can be assigned its value with destructuring separate from its declaration.

let a,b;
({a, b} = {a: 1, b: 2});
let a, b;
{a, b} = {a: 1, b: 2}; // this is not valid in this case
//{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

8. Aliases:

If we want to create variable name other than property name then we can use aliasing feature of object destructuring.

const { prop: newVaribleName } = object;
const {a: aa} = {a: 3};
console.log(aa); // 3

we can also use default value feature with alias.

const {a: aa = 10, b: bb = 5} = {a: 3};

console.log(aa); // 3
console.log(bb); // 5

9. Nested object and array destructuring:

Sometimes we have an object which consists of an array of the object also. We can destructuring this kind of object also.

const user= {
  name: 'Singhak.in',
  education: [
    {
      highSchool: '70',
      btech: '74',
      mtech: '75'
    }
  ],
  website: 'https://singhak.in'
};

let {
  name: fullname, // rename
  education: [
    {
      highSchool, btech
    },
  ],
} = user;

console.log(fullname); // "singhak.in"
console.log(highSchool);  // "70"

10. Extracting a dynamic name property:

You can extract to variables properties with a dynamic name (the property name is known at runtime):

const { [propName]: identifier } = object;
let key = 'z';
let {[key]: foo} = {z: 'bar'};
console.log(foo); // "bar"

11. Rest in Object Destructuring:

let {a, b, ...other} = {a: 10, b: 20, c: 30, d: 40}
a; // 10 
b; // 20 
other; // { c: 30, d: 40 }

12. Setting a function parameter’s default value:

function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25}) {
  console.log(size, coords, radius);
  // do some chart drawing
}

drawChart({
  coords: {x: 18, y: 30},
  radius: 30
});

13. Combined Array and Object Destructuring:

const props = [
  { id: 1, name: 'Fizz'},
  { id: 2, name: 'Buzz'},
  { id: 3, name: 'FizzBuzz'}
];

const [,, { name }] = props;

console.log(name); // "FizzBuzz"

References:

Leave a Reply