# How to swap two array elements in JavaScript

> Learn how to swap two elements in a JavaScript array, both with a temporary variable and with a one-line destructuring assignment that needs no temp.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-08-09 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/javascript-swap-array-elements/

How do you swap 2 elements in an array, in [JavaScript](https://flaviocopes.com/javascript/)?

Suppose we have an array `a` which contains 5 letters. 

```js
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:

```js
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:

```js
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.

```js
a //[ 'a', 'b', 'c', 'd', 'e' ]
```
