ES6: Unintuitive array element swapping using destructuring assignment

Found this tricky scenario when trying to sort an array by swapping elements using destructuring assignment.

// try to sort the array by swapping elements
const a = [2, 1];

// does not work
// 1. cache values on right side of =, i.e. [1, 2]
// 2. a[0] := 1; a is now [1, 1]
// 3. a[a[0]-1] = a[1-1] = a[0] := 2; a is now [2, 1] again
[a[0], a[a[0]-1]] = [a[a[0]-1], a[0]];
console.log(a); // [2, 1]

// does work
// 1. cache values on right side of =, i.e. [2, 1]
// 2. a[a[0]-1] = a[2-1] = a[1] := 2; a is now [2, 2]
// 3. a[0] := 1; a is now [1, 2]
[a[a[0]-1], a[0]] = [a[0], a[a[0]-1]];
console.log(a); // [1, 2]

// seems like the values on the right of the = are cached first, then each assignment is executed in order from left to right.
// if latter assignments depend on values of previous assignments, this will cause unintuitive results

Here’s a nodejs REPL

#javascript #node-js

6 Likes1.45 GEEK