Using Destructuring to Swap Values
Version: ES2015
Level: Intermediate
Normally, when you swap two values, you have to create a temporary variable to keep one of the original values so it doesn’t get lost when assigning from the other.
let one = 1;
let two = 2;
// swap
let temp = one;
one = two;
two = temp;
console.log(one); // 2
console.log(two); // 1
With array destructuring, this can be done more easily and all in the same line. With a destructuring list of your two variables, you can swap them by assigning them to an array of their values in reverse order.
let one = 1;
let two = 2;
[one, two] = [two, one]; // swap
console.log(one); // 2
console.log(two); // 1
Though it may look like the temporary variable is gone, we still have it in the form of the array being assigned. Each one
and two
are temporarily stored as elements in that array so that when the assignments occur, they’re being pulled from the array and not the originals. This is effectively the same as:
let one = 1;
let two = 2;
// swap
let temp = [two, one];
one = temp[0];
two = temp[1];
console.log(one); // 2
console.log(two); // 1
Because destructuring ultimately boils down to standard assignment operations, you can also do this with individual array elements and object properties.
let list = [1,2,3,4,5];
[list[0], list[1]] = [list[1], list[0]]; // swap
console.log(list); // [2, 1, 3, 4, 5]
let nums = { one: 1, two: 2 };
[nums.one, nums.two] = [nums.two, nums.one]; // swap
console.log(nums); // {one: 2, two: 1}
When dealing with arrays, you’ll want to be sure not to destructure from the original array since each assignment happens sequentially and you might be assigning from a value assigned earlier in the destructuring.
let list = [1,2,3,4,5];
[list[1], list[0]] = list; // avoid
console.log(list); // [1, 1, 3, 4, 5]
Here, list[1]
was assigned first. Then when list[0]
was getting assigned, it was getting its value from the just-assigned list[1]
rather than a temporary array which would have kept the values separated.
More info: