Javascript swap array elements

You only need one temporary variable.

var b = list[y];
list[y] = list[x];
list[x] = b;

Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts:

Given the array arr = [1,2,3,4], you can swap values in one line now like so:

[arr[0], arr[1]] = [arr[1], arr[0]];

This would produce the array [2,1,3,4]. This is destructuring assignment.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)