How to swap variables using destructuring assignment in JavaScript ?

Destructuring assignment is a feature introduces in EcmaScript2015 which lets you extract the contents of array, properties of object into distinct variables without writing repetitive code.
Example 1: Here in this example we declared two variables a and b unassigned and an array with two strings “First” and “Second” int it. On line 5 we used destructuring assignment to assign values of array to and b respectively.
Javascript
<script> Â Â let a; Â Â let b; Â Â let array = ["First", "Second"]; Â Â Â Â [a, b] = array; Â Â console.log("a:", a); Â Â console.log("b:", b); </script> |
Output:
a: First b: Second
As you can see variable a has string “First” assigned and variable b has string “Second” assigned.
Example 2: Here we declared two variables a and b having values “First” and “Second” respectively. In the next line we swapped variables using destructuring assignment.
Javascript
<script> Â Â let a = "First"; Â Â let b = "Second"; Â Â [a, b] = [b, a]; Â Â Â Â console.log("a:", a); Â Â console.log("b:", b); </script> |
Output:
a: Second b: First



