Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Swapping two array elements in a single line using JavaScript

  • Last Updated : 15 Mar, 2021

In JavaScript, there exist many ways using 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

This swapping can be done by writing the 2 array elements we 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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

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

Example 1:



Javascript




<script>
  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)
</script>

Output:

[1, 2, 3, 4, 5]

Example 2:

Javascript




<script>
  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);
</script>

Output:

['a','b','c','d','e']
My Personal Notes arrow_drop_up
Recommended Articles
Page :