Swap Without Temp
Array destructuring lets you swap two variables in one line without a temporary variable.
Array destructuring lets you swap two variables in one line without a temporary variable.
let x = 1, y = 2;
[x, y] = [y, x]; // x=2, y=1
// Multi-swap
let a = 1, b = 2, c = 3;
[a, b, c] = [b, c, a]; // rotate: a=2, b=3, c=1
// Practical: rotate array elements
const arr = [1, 2, 3, 4];
[arr[0], arr[arr.length - 1]] = [arr[arr.length - 1], arr[0]]; // swap first and last
Variable swap via destructuring is idiomatic JS — no temp variable, no XOR trick.
More in JavaScript