Question: What is best practice for switching two items place in an Array via JavaScript?

For example if we have this array `['one', 'two', 'three', 'four', 'five', 'six']` and want to replace two with five to get this final result: `['one', 'five', 'three', 'four', 'two', 'six']`.

![enter image description here](https://i.stack.imgur.com/CK1DO.png)

The ideal solution is short and efficient. 

Update:

The `var temp` trick is working and I know it. My question is: is using [JavaScript native Array methods](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Methods) faster or not? 

Something like `array.splice().concat().blah().blah()` seems is faster and use less memory. I didn't develope a function that using Array methods but I'm sure it's possible.

Answer: 
Just use a variable as temporary storage:

```
var temp = data[1];
data[1] = data[4];
data[4] = temp;

```

As this just copies values in the array it avoids methods like slice and splice that move around big parts of the array or creates entirely new arrays, which would be very expensive in comparison, and also scales badly. This is an O(1) operation, while splicing would be an O(n) operation where n is the number of items that would be moved, which would be something like length\*2-index1-index2.

Here is a performance test for different ways of swapping the items: <http://jsperf.com/array-item-swap/2>

Even if you use `splice` in a way so that it would not need to move around a lot of data, it's still slow. Copying the values is about 50 times faster.
It looks like Guffa beat me to it but here's a function (and working example) that would work.

<http://jsfiddle.net/neilheinrich/Hu389/>

```
var my_array = [1, 2, 3, 4, 5, 6];

var swapArrayPosition = function (array, index_1, index_2) {
  var temp = array[index_1];
  array[index_1] = array[index_2];
  array[index_2] = temp;
}

swapArrayPosition(my_array, 4, 1);

```