Skip to content

How to swap two array elements in JavaScript

How do you swap 2 elements in an array, in JavaScript?

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).

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

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' ]
→ Download my free JavaScript Handbook!



You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about js: