In the past, swapping the values of two variables in JavaScript required an intermediate variable to store one of the values while swapping, which would result in something similar to this:
let a = 10;
let b = 20;
let tmp;
= a;
tmp = b;
a = tmp; b
While this approach still works, there are more elegant and less verbose options available to us nowadays. For example, JavaScript ES6 introduced destructuring assignments, allowing individual array items to be assigned to variables in a single statement. Here’s what that looks like:
const [x, y] = [1, 2];
Destructuring assignments are extremely useful in a handful of situations, including swapping two variables. To accomplish this, we can create an array from the two variables, then use a destructuring assignment to reassign them to each other:
let a = 10;
let b = 20;
, b] = [b, a]; [a