DEV Community

Cover image for JavaScript One Line Array Element Swap
Hunter Heston
Hunter Heston

Posted on • Updated on

JavaScript One Line Array Element Swap

Use Object Destructuring to Swap Elements

const arr = [1,2,3,4];

[arr[0], arr[2]] = [arr[2], arr[0]];

console.log(arr);
Enter fullscreen mode Exit fullscreen mode

Explanation

On the right-hand side, we are creating a new array of [3, 1]. We immediately use destructuring assignment to override the values at position arr[0] and arr[2].

It's a good trick to swap elements that I thought I could share.

Thanks for reading!

Top comments (0)