Destructuring Assignment in JavaScript

     The destructuring Assignment is used to unpack values from an array or objects into distinct variables.

Example:

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

Syntax:

         const [a,b,...rest] = array 
         const {a, b, ...rest} = object


Consider the following examples:

          const arr =[1,2,3,4,5]
          const [a,b] = arr
          console.log(a,b) //output: 1,2

          const [x,y,...newArr] = arr;
          console.log(x, y, newArr) //output: 1,2,[3,4,5]


Similarly,

          const obj = {pid:1618, name:'process'}
          const {pid, b} = obj
          console.log(pid, b) //output: 1618 undefined

Note: Remember while destructuring an object, the variable name should be same as key, otherwise it will contain an undefined value as b in the above example.

           const {pid, name} = obj
           console.log(pid, name) //output: 1618, process


If in an object the value is not present or undefined, in that case we can assign some default value while destructuring as

          const obj = {pid:1618,name:'process'}

          const {pid, b="default"} = obj

          console.log(pid, b) //output: 1618 default


Assigning a new variable name while destructuring object:

          const obj = {pid:1618, name:'process'}

          const {pid:a, name:b} = obj

          console.log(a, b) //output: 1618 process


Continue Learning: JavaScript Array

Comments

Popular Posts