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 ofain thearray. We need to hold this value in a variable to refer to it later.Then, we set the value of
ainarrayto the value ofbinarray.Finally, we set the value of
binarrayto the value of ourtempvariable. Notice that we can't set it to the value ofainarrayas 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
swapfrom ES6. - This function takes the same arguments:
array,a,b - Instead of requiring the
tempvariable, we can simply assign thearray's value ofaandbto the respective opposite value on the right side of the equal sign.
Top comments (0)