JavaScript: 4 Ways to Swap Elements in an Array

Updated: March 9, 2023 By: Khue Post a comment

This concise example-based article will walk you through 4 different approaches to swapping elements in a given array in JavaScript.

Using the array destructing syntax

Array destructuring is a JavaScript expression that allows us to extract data from arrays or iterable objects into separate variables.

In the context of swapping elements in an array, we can use array destructuring to assign the values of the two elements to be swapped to separate variables and then assign them back to their new positions in the array.

In the example below, we will swap the position of the first Element (with Index 0) and the fourth element (with Index 3):

const array = ['A', 'B', 'C', 'D', 'E'];
[array[0], array[3]] = [array[3], array[0]];


[ 'D', 'B', 'C', 'A', 'E' ]

As you can see, we only need a single line of code to do the swapping job.

Using a temporary variable

This is a classic technique in programming, and it is quite understandable.


let array = ['A', 'B', 'C', 'D', 'E'];
let temp = array[1];
array[1] = array[3];
array[3] = temp;


[ 'A', 'D', 'C', 'B', 'E' ]

Using the Subtraction Method

The subtraction method involves subtracting one element from the other to swap their values. This method only works if the two elements being swapped are numeric values.


const array = [1000, 2000, 3000, 4000];

// swap 2000 and 4000
array[1] = array[1] - array[3];
array[3] = array[1] + array[3];
array[1] = array[3] - array[1];



[ 1000, 4000, 3000, 2000 ]

If you are a person who likes the beauty of mathematics, this method will suit you.

Using the splice() method

Another possible solution is to use the splice() method, which can remove and insert elements in an array.


let arr = ['sling', 'academy', 'dot com']; 

// swap first and third elements 
arr[0] = arr.splice(2, 1, arr[0])[0]; 



[ 'dot com', 'academy', 'sling' ]

Closing Thoughts

All mentioned approaches in this article are decent and concise. However, most developers prefer and use one of the first two methods. How about you? Let us know your opinion by leaving a comment.