Swap Array Elements with JavaScript's ES6
Samantha Diaz
Posted on July 12, 2022
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;
}
Code Breakdown
We define a function called
swap
, and pass in arguments for anarray
, variablea
, and variableb
. These represent the values we want to swap.Next, we declare a temporary variable,
temp
, and set that equal to the value ofa
in thearray
. We need to hold this value in a variable to refer to it later.Then, we set the value of
a
inarray
to the value ofb
inarray
.Finally, we set the value of
b
inarray
to the value of ourtemp
variable. Notice that we can't set it to the value ofa
inarray
as we have already changed that to equalb
's value.
BUT - with ES6, there's a simpler way!
const swap = (array, a, b) => {
[array[a], array[b]] = [array[b], array[a]];
};
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 thearray
's value ofa
andb
to the respective opposite value on the right side of the equal sign.
Posted on July 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024