Search code examples
javascriptswapdestructuringecmascript-2016

How does this function to swap array elements work?


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)


Solution

  • Starting with the righthand side:

    [a[j], a[i]]
    

    This creates a new array with two elements: the element at index j, followed by the element at index i.

    On the left hand side it's doing destructuring

    [a[i], a[j]] = 
    

    So that's the equivalent of the following:

    a[i] = theNewArray[0];
    a[j] = theNewArray[1];
    

    Since this is mutating a, those changes can be felt by any references to the array, so data will "see" the changes.