I saw this function on here that will swap two array elements but I can't seem to figure out how it works. It looks like there is some sort of array destructuring going on (?). I just don't understand how and why the original data
-array is actually changed.
Can someone please explain to me how this works?
const swap = (a, i, j) => {
[a[i], a[j]] = [a[j], a[i]] // ???
}
const data = [1, 2, 3, 4]
swap(data, 0, 2)
console.log(data)
Starting with the righthand side:
This creates a new array with two elements: the element at index
j
, followed by the element at indexi
.On the left hand side it's doing destructuring
So that's the equivalent of the following:
Since this is mutating
a
, those changes can be felt by any references to the array, sodata
will "see" the changes.