Explain Codes LogoExplain Codes Logo

Swap array elements in JavaScript

javascript
promises
callbacks
functions
Nikita BarsukovbyNikita Barsukov·Oct 13, 2024
TLDR

Swap elements in a JavaScript array instantly using ES6 destructuring:

let array = ['a', 'b', 'c']; // Swapping 'b' and 'c', just like magic! [array[1], array[2]] = [array[2], array[1]];

Two lines: define array, swap with brackets—no extra variables. It's like slicing bread... but neat!

Temporary variable: the veteran's way

The classic, old-school approach to array element swapping involves a temporary variable. This style dates back to the ancient times where programmers had beards and wore robes. Still sharp, though!

var temp = array[1]; // This is where we store our 'b' array[1] = array[2]; // 'b' makes way for 'c' array[2] = temp; // 'b' is back, this time in place of 'c'

It's a bit more verbose than ES6, but hey, it's compatible with almost every JS environment out there!

Spice it up with .splice()

A little-known fact: the splice method can also perform swapping. This method might just add some zest to your code:

// Now you see 'b', now you don't! Oh wait, it's back -- but in place of 'c'! array.splice(1, 1, array.splice(2, 1, 'd')[0]);

Enhanced swaps for advanced coders

DRY approach with a swap function

DRY (Don’t Repeat Yourself) maintains that you should never have to write the same piece of code twice. Here’s how you can create a function to do the job quickly and efficiently :

Array.prototype.swap = function (x, y) { // Swapping elements like there's no tomorrow. [this[x], this[y]] = [this[y], this[x]]; };

Now, whenever you need to swap, just call array.swap(x, y). This way, all arrays get this honor for free!

Performance matters

Performance is the king for large arrays. Although ES6 destructuring is cool, it may be slower than a temporary variable due to creation of subarrays. So remember: size matters!

Compatibility and debug tips

Backward compatibility

In browsers or environments, where new-fangled ES6 hasn't made a lodgement yet, destructuring won't work. Here, your best friends will be good old temporary variables or splice.

Debug with style

Swapping incorrectly could lead to bugs wearing camo! Ensure the indices used for swapping are valid and don't forget that JavaScript arrays are zero-indexed. That's one off your count!

Going beyond

Sometime, you may need to swap non-adjacent elements, multiple pairs or implement circular swaps. These require a more sophisticated dance of logic, often involving loop constructs or mapping strategies.