Destructuring Assignment in JavaScript
The destructuring Assignment is used to unpack values from an array or objects into distinct variables.
Example:
let [a,b] = arr;
console.log(a,b) //output: 1,2
Syntax:
const {a, b, ...rest} = object
Consider the following examples:
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 {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.
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
Comments
Post a Comment