DEV Community

Best way to Swapping in JavaScript

Mohammed Awad on June 11, 2023

Have you ever needed to swap the values of two variables in JavaScript? While it may seem simple at first, directly swapping the values (head = ta...
Collapse
 
juliofagundes profile image
Julio Fagundes • Edited

Simple and clearly solution for beginners! Nice done Muhmmad.

// If you want to go deep, destructuring assignment is also a good way
[head, tail] = [tail, head]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
xmohammedawad profile image
Mohammed Awad • Edited

thanks, ChatGPT told me that wrong with primitive type like number. and [a, b] = [b, a] will not work and it's use jsut for swaping array elemnts . but now you and other told me that. I checked by self and saw that ChatGPT wrong . wow

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
[a, b] = [b, a]
Enter fullscreen mode Exit fullscreen mode

No temporary variable needed.

Collapse
 
xmohammedawad profile image
Mohammed Awad

thanks, ChatGPT told me that wrong with primitive type like number. and [a, b] = [b, a] will not work and it's use jsut for swaping array elemnts . but now you and other told me that. I checked by self and saw that ChatGPT wrong . wow

Collapse
 
jonrandy profile image
Jon Randy 🎖️

ChatGPT is frequently wrong. I'd trust it as far as I could throw it - with programming, and almost anything TBH

Collapse
 
codingjlu profile image
codingjlu

You should never do this in real life, but these are great for confusing your colleagues (only works on integers).

👍

x += y
y = x - y
x -= y
Enter fullscreen mode Exit fullscreen mode

😎

x *= y
y = x / y
x /= y
Enter fullscreen mode Exit fullscreen mode

🤯

x ^= y
y ^= x
x ^= y
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ashishk1331 profile image
Ashish Khare😎

Now here is the real treasure 😉
Great one.

Collapse
 
codingjlu profile image
codingjlu

I agree; the only benefit there is saving the memory for 8 bytes or the like. Speed wise it's found lacking.

Collapse
 
panayiotisgeorgiou profile image
Panayiotis Georgiou

very good 😀

Collapse
 
xmohammedawad profile image
Mohammed Awad

glad to hear that

Collapse
 
ashishk1331 profile image
Ashish Khare😎

The comment section is on fire 🔥.

Collapse
 
xmohammedawad profile image
Mohammed Awad

🔥🔥🔥

Collapse
 
vjnvisakh profile image
Visakh Vijayan

Like the effort

Collapse
 
xmohammedawad profile image
Mohammed Awad

thank you

Collapse
 
xmohammedawad profile image
Mohammed Awad

sometimes It's simplified hard lectures. If I didn't understand something I ask his to expalin it for me . but from now on I will careful with every answer I get from him

 
xmohammedawad profile image
Mohammed Awad

You are 100% right

Collapse
 
xmohammedawad profile image
Mohammed Awad

Do you like the article or just swap? :)