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' ]

→ Get my JavaScript Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list