Back

Swap like a boss in Javascript

Swap like a boss in Javascript

Swapping is something we usually encounter during our coding work.

Ask any developer, let alone Javascript devs how they swap elements in an array, and 99.9% of them would respond in this manner:

function swap(arr: number[], start: number, end: number) {
    const temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
}

This is a very common pattern, and works just fine. However, there's an even easier way to do so in Javascript which once you get to know it, makes it super easy to swap elements in an array in-place.

Here's an example:

function swapLikeABoss(arr: number[], start: number, end: number) {
    [arr[start], arr[end]] = [arr[end], arr[start]];
}

The code above has the same output as before, it swaps the elements in start and end in-place (meaning, O(1) space complexity), but this way is much more intuitive and doesn't require you to use the temp variable.

Also, you can use it to easily swap elements in a non-symmetrical way, and makes the mind model much easier (in my opinion, at least)