DEV Community

Samantha Diaz
Samantha Diaz

Posted on

Swap Array Elements with JavaScript's ES6

If you are solving a problem and it requires you to swap elements in an array, you might create a function like this:

function swap(array, a, b){
    let temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}
Enter fullscreen mode Exit fullscreen mode

Code Breakdown

  • We define a function called swap, and pass in arguments for an array, variable a, and variable b. These represent the values we want to swap.

  • Next, we declare a temporary variable, temp, and set that equal to the value of a in the array. We need to hold this value in a variable to refer to it later.

  • Then, we set the value of a in array to the value of b in array.

  • Finally, we set the value of b in array to the value of our temp variable. Notice that we can't set it to the value of a in array as we have already changed that to equal b's value.

BUT - with ES6, there's a simpler way!

const swap = (array, a, b) => {
    [array[a], array[b]] = [array[b], array[a]];
};
Enter fullscreen mode Exit fullscreen mode

This uses Destructuring Assignment to separate the elements of the array into values that can be reassigned.

Code Breakdown

  • To make the code more compact, we declare the function using an arrow function named swap from ES6.
  • This function takes the same arguments: array, a, b
  • Instead of requiring the temp variable, we can simply assign the array's value of a and b to the respective opposite value on the right side of the equal sign.

Top comments (0)