Swapping Array Elements In Place, Destructuring, and Automatic Semicolon Insertion

Stephen Charles Weiss Originally published at stephencharlesweiss.com on ・2 min read

About a year ago, I learned about bitwise operators and using them to swap elements of a list in place.

With Array Destructuring, Javascript now allows you to do this without relying on bitwise operators.

For example to swap the first and fourth element, you might do the following:

const arr = [1, 2, 3, 4, 5]

[(arr[0], arr[3])] = [arr[3], arr[0]]


Did you catch the error?

There’s no ; to end the definition of the array. This is not a case where Javascript’s Automatic Semicolon Insertion (ASI) will add one either. 1 Instead, if you tried to run this code, you’d get an error similar to:

~/Users/Stephen/Desktop/scratch.js:15~
[arr[0], arr[3]] = [arr[3], arr[0]];
^

ReferenceError: arr is not defined
at anon (~/Users/Stephen/Desktop/scratch.js:15:4~)
at Object.<anonymous> (~/Users/Stephen/Desktop/scratch.js:18:1~)
at startup (internal/bootstrap/node.js:285:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)


We can fix it with a well-placed ;:

const arr = [1, 2, 3, 4, 5];

[(arr[0], arr[3])] = [arr[3], arr[0]]

console.log(arr) // [4, 2, 3, 1, 5]


Tracking down the error was a fun reminder about the costs of being clever. Sometimes using a simple swap function really is just the right way to go:

function swap(list, x, y) {
const tmp = list[x]
list[x] = list[y]
list[y] = tmp
return list
}


Footnotes

Posted on by:

Stephen Charles Weiss

Engineer | Lover of dogs, books, and learning | Dos XX can be most interesting man in the world, I'm happy being the luckiest. | I write about what I learn @ code-comments.com