Swap Variable Values Without a Temporary Variable with Array Destructuring
A common interview question is "Swap the variable values."
Usually the solution involves a temporary variable. But we can solve this easily with a destructuring trick.
We can use destructuring to swap the values of two variables without the need for a temporary variable:
let a = 1; let b = 2; console.log(a); // 1 console.log(b); // 2 [a, b] = [b, a]; console.log(a); // 2 console.log(b); // 1
Now you have the most elegant solution. 😉