JavaScript

Swap two, three of more values in JavaScript

Best and easiest way to swap two, three of more values in JavaScript.
A corgi smiling happily

Here is the way:

1let [a, b, c] = [10, 20, 30]
2
3;[a, b, c] = [b, c, a]
4
5// swapped: a = 20, b = 30, c = 10
6
7let [d, e] = [40, 50]
8
9;[d, e] = [e, d]
10
11// swapped: d = 50, e = 40

Now lets jump into details. For swapping, traditionally I used to do with temporary variable, like:

1let a = 10,
2 b = 20
3
4let temp = a
5a = b
6b = temp
7
8// a = 20, b = 10

But there was a better way to same in python:

1a = 10
2b = 20
3
4a, b = b, a
5
6# a = 20, b = 10

and then come the es6 with the array destructuring, like:

1let [a, b] = [10, 20]
2let [c, d, e, ...rest] = [30, 40, 50, 60, 70, 80]
3
4// a = 10, b = 20, c = 30, d = 40, e = 50, rest = [60, 70, 80]

so, we can use the array destructuring to swap the value.

Here is a bubble sort function to understand it better:

1function bubbleSort(array) {
2 let isSorted = false
3 while (!isSorted) {
4 isSorted = true
5 for (let i = 0; i < array.length - 1; i++) {
6 if (array[i] > array[i + 1]) {
7 isSorted = false
8 [array[i], array[i + 1]] = [array[i + 1], array[i]]
9 }
10 }
11 }
12 return array
13}

🙏

Do you have any questions, or simply wish to contact me privately? Don't hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.