JavaScript

## Swap two, three of more values in JavaScript

###### Best and easiest way to swap two, three of more values in JavaScript.  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 = 106
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 = 203
4let temp = a5a = b6b = temp7
8// a = 20, b = 10```

But there was a better way to same in python:

```1a = 102b = 203
4a, b = b, a5
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 = false3  while (!isSorted) {4    isSorted = true5    for (let i = 0; i < array.length - 1; i++) {6      if (array[i] > array[i + 1]) {7        isSorted = false8        [array[i], array[i + 1]] = [array[i + 1], array[i]]9      }10    }11  }12  return array13}`

🙏

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 🙏