How to swap two array elements in JavaScript
By Flavio Copes
Learn how to swap two elements in a JavaScript array, both with a temporary variable and with a one-line destructuring assignment that needs no temp.
You can swap two array elements in JavaScript in two ways: with a temporary variable, or in one line with a destructuring assignment. Let’s see both.
Suppose we have an array a which contains 5 letters.
const a = ['a', 'b', 'c', 'e', 'd']
We want to swap element at index 4 (‘d’ in this case) with the element at index 3 (‘e’ in this case).
The temporary variable approach
We can use a temporary item tmp to store the value of #4, then we put #3 in place of #4, and we assign the temporary item to #3:
const tmp = a[4]
a[4] = a[3]
a[3] = tmp
The temporary variable is needed because the moment you write a[4] = a[3], the original value at index 4 is gone. tmp keeps a copy of it so we can place it at index 3 afterwards.
This is the classic swap, and it works in any language.
The destructuring approach
Another option, which does not involve declaring a temporary variable, is to use this syntax:
const a = ['a', 'b', 'c', 'e', 'd'];
[a[3], a[4]] = [a[4], a[3]]
Now the array a will be correctly ordered as we want.
a //[ 'a', 'b', 'c', 'd', 'e' ]
Here’s what happens: the right side builds a new two-element array with the current values, ['d', 'e']. Then the destructuring assignment writes those values back into a[3] and a[4], in swapped order. No temporary variable, because the intermediate array plays that role.
Notice that we declared a with const and we can still swap its elements. const prevents reassigning the variable, not mutating the array it points to.
Be careful with the semicolon
Did you spot the semicolon after the array declaration? It’s there on purpose, and this is the pitfall of the destructuring approach.
If you write code without semicolons and the previous line ends with a value, JavaScript merges the two lines. The [ gets interpreted as accessing an index on whatever came before, and you get an error like:
ReferenceError: Cannot access 'a' before initialization
or a silent bug, depending on the surrounding code. A line that starts with [ needs a semicolon before it, either at the end of the previous line or right at the start:
;[a[3], a[4]] = [a[4], a[3]]
Both approaches mutate the array in place. If you need the original untouched, copy it first with const sorted = [...a] and swap the elements of the copy.
Related posts about js: