Oliver Jumpertz

Swap Array Elements Inline

Category: JavaScript

Share this snippet to:

const array = [1, 2, 3];
[array[0], array[2]] = [array[2], array[1]];
// array is now [3, 2, 1]

Explanation

Array destructuring also works for index references to arrays. In this case, you basically tell the runtime the following:

Take the value at array[2] and place it inside array[0], and then take the value at array[0] and place it at array[2], while implicitly creating a temporary variable because you don’t want to lose the original values.

The runtime creates the temporary variable automatically for you, under the hood, so you don’t have to deal with it in your code.

Without array destructuring, your code would look like this:

const array = [1, 2, 3];
const tmp = array[0];
array[0] = array[2];
array[2] = tmp;

Share this snippet to: