What is Destructuring in javascript?

Destructuring assignment: destructuring assignment can extract value in single variable from the array and object properties. The destructuring assignment syntax is a JavaScript expression. We can assign an array in the variable and then access it as below example:

const numbers = [123];

[num1, num2] = numbers;

console.log(num1, num2); // output: 1 2

 

const numbers1 = [123];

[num1, , num3] = numbers1;

console.log(num1, num3); // output: 1 3

 

Destructuring assignment with rest operator.

let x, y, rest;

[x, y] = [5'b'];

console.log(x);// output: 5

console.log(y);// output: "b"

 

[x, y, ...rest] = [57'c''d'5];

console.log(rest);// output: Array ["c", "d", 5]

 

Also we can swap value with destructuring assignment.

// swapping array value

const arr = [5,7,9];

[arr[0], arr[1]] = [arr[1], arr[2]];

console.log(arr); // [7, 9, 9]

 

Destructuring assignment using with default value.

 

// defualt value

let ss1, ss2;

 

[ss1=15, ss2=17] = [1];

console.log(ss1); // 1

console.log(ss2); // 17

 

We are accessing value from porperty name of the object.

// sytax destructuring for the object

({ } = { });

({ x, y } = { xx: 5, y: 7 });

console.log(x); // undefined

console.log(y); // 7

 

More destructuring example for the objects.

 

({ aa, b } = { a: 10, b: 20, dd:'Sheo' });

console.log(a); // a is not defined 

console.log(b); // 20

console.log(dd); // dd is not defined

 

// Need to define dd porperty name 

({ aa, dd, b } = { a: 10, b: 20, dd:'Sheo' });

//console.log(a); // a is not defined

console.log(b); // 20

console.log(dd); "Sheo"

 

({ x, y } = { x: 5, y: 7 });

console.log(x); // 5

console.log(y); // 7

 

({a, b, ...rest} = {a: 11, b: 13, c: 15, d: 117});

console.log(a); // 11

console.log(b); // 13

console.log(rest); // {c: 15, d: 117}

 


 

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.