Thursday, September 4, 2025
HomeLanguagesJavascriptSwapping two array elements in a single line using JavaScript

Swapping two array elements in a single line using JavaScript

In JavaScript, there exist many ways by which one can swap two array elements. In this article, we will discuss a way in which one can swap two array elements in JavaScript in a single line. The input and output would be as follows.

Input: arr = { 10, 20, 40, 30 }
Output: arr = { 10, 20, 30, 40 }
// Swapped 30 and 40

Approach: Using Destructuring Method

This is a far better method than anyone. This method can be executed in a single line. This swapping can be done by writing the 2 array elements and want to reverse in order and in square brackets on the left-hand side. On the right-hand side, we will write the same array elements but this time in reverse order. We can also create a reusable function that can swap the specified index of the array.

Syntax:

[a[m], a[n]] = [a[n], a[m]] 
 
// Where m and n are the index numbers to swap

Example 1: In this example, we will swap two number array elements in a single line using JavaScript.

Javascript




let arr = [1, 2, 3, 5, 4];
 
// Swapping element at index 3 with
// index 4
[arr[3], arr[4]] = [arr[4], arr[3]];
 
// Print the array
console.log(arr);


Output

[ 1, 2, 3, 4, 5 ]

Example 2:  In this example, we will swap two string array elements in a single line using JavaScript.

Javascript




let arr = ["e", "b", "c", "d", "a"];
 
// Swapping element at index 0 with
// index 4
[arr[0], arr[4]] = [arr[4], arr[0]];
 
// Print the array
console.log(arr);


Output

[ 'a', 'b', 'c', 'd', 'e' ]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS