Destructuring in ES6

Destructuring in ES6 is all about unpack the values from arrays, or properties from objects, into distinct variables.

  1. Array Destructuring
  2. Object Destructuring

Destructuring in ES6

Destructuring in ES6

1.Array Destructuring:

  • We will understand array destructuring by example lets start
  • let’s take basic way of doing destructuring
  • Now the example below shows that array demo has three values “demo1″,”demo2” and “demo3”
  • When we assign the array demo like var [demo1, demo2, demo3] = demo; this is called destructuring
  • Now each value of array will be assign to subsequent variables

Array assingment with default values of variable:

  • For below example varibles already have values x=5 and y=7
  • Second thing is we are destructuring [2] into [x=5, y=7] but x already have value 5.
  • the questing arises what will happen with x then as the result x will be overriden with value 2 hence the output for the x will be 2

Array assignment with swapping values

Sometime in interview interviewer asks such questions that you have to swap values in single statement the we can use below statement

Function array returned as destructured way

In below example function is returning values and we are collecting those values in destructured way

Rest operator with destructuring

  • Here we have destructured in two variable one a and …b now the values [1, 2, 3] will be destructured in such way that
    a will be assigne with first value i.e. 1
  • …b will be assigned rest of the values 2, 3 as an array

Ignoring the values in destructuring

  • See below example while destructuring a will be assigned with 1 and b is assigned with 3 but the value 2 is ignored

2.Object Destructuring

  • The object obj = {x: 42, y: 23}; will be destructured in such way that
    {x, y} values will be
  • x will be 42 the value of x property of the object obj
  • y will be 23 as the value of y property of the object obj

Assignment with different variable name:
In above example we have used x and y which are same as x and y of the obj
But when we want different variable names then we can use following way

Object destructuring with default values:

  • Below example we have already defined values in the destructured object x=3 and y =6
  • But when we assign {x: 3} then the value of x becomes 3 when we print we will get x as 3

 

Leave a Reply

Your email address will not be published. Required fields are marked *