DEV Community

loading...
Cover image for JavaScript One Line Array Element Swap

JavaScript One Line Array Element Swap

Hunter Heston
I am a embedded software engineer but I also like working with JavaScript.
・1 min read

Use Object Destructuring to Swap Elements

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

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

console.log(arr);

Explination

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!

Discussion (0)