Destructuring to Reduce Temporary Variables
Swapping the values of two variables is taught by introducing a temporary variable. For example:
let a = 1;
let b = 2;
let tmp = b;
b = a;
a = tmp;
Array destructuring can be used to shrink the code. For example:
let a = 1;
let b = 2;
[a,b] = [b,a];
The right side of the expression is evaluated before any assignment is made, and thus the swap occurs. Of course in dynamic languages like JavaScript this will hurt performance as it will likely create and then destroy an array. In a compiled language, like rust, the optimizer will make the code just as performant.
A more practical example of temporary variables is in the Euclidean Algorithm to find the greatest common divisor.
fn gcd(mut a: usize, mut b: usize) -> usize {
while b != 0 {
let t = b;
b = a % b;
a = t;
}
a
}
This can be simplified using the destructuring trick:
fn gcd(mut a: usize, mut b: usize) -> usize {
while b != 0 {
[a,b] = [b, a % b];
}
a
}
According to Compiler Explorer, these examples compile to the same assembly.
With any trick like this, programmers will debate whether its worthwhile. I personally think it more concisely describes the logic, but the syntax might be unfamiliar to some.