In javaScript, the "Destructing"
technique lets you extract information from an array or an object and assign it to any variable you want easily.
for example, if you have an array and want to assign its first values to another two separate variables, you can use the array index
like this:
let a, b;
let arr = [6, 2, 3, 5];
a = arr[0];
b = arr[1];
console.log(a, b); // output: 6 2
Then in ES6
you can do the same but in one line using Destructing
:
let a, b;
let arr = [6, 2, 3, 5];
[a, b] = arr;
console.log(a, b) // output: 6 2
Here, this is Array Destructing
you have an array on the right-hand side and another array on the left-hand side, what JavaScript will do is that it will take the first value in the right-hand side array and assign it to the first variable in the left-hand side array ( the same for b
variable).
As mentioned in the lesson, if you want to get a specific value in the array, you can use commas until you reach the value you want to get ( to destruct ).
Back to your case, you need to swap a
and b
values, so you can use the array destructing way to do it in one line,
assume that
a is 8
b is 10
so, you will make an array on the right-hand side using those values in order like [8, 10]
or [a, b]
, and on the left-hand side make an array with the variables names but reversed like [b, a]
.
[b, a] = [a, b];
That way, if you followed how destructing works, you will see that b
is now 8 and a
is now 10.
sorry my super long answer.