DEV Community

loading...

Discussion on: Swap two numbers without using a temporary variable

Collapse
michaelphipps profile image
Phippsy

Great post. Cool trick! Thanks for introducing me to codedrops.tech!

Serious question though - why would you avoid using the temporary variable?

let x = 5, y = 3, temp = null;
temp = x;
x = y;
y = temp;
console.log(x,y);  // 3 5
Enter fullscreen mode Exit fullscreen mode

Just about the same number of characters, more clear what is being done.

Collapse
kenbellows profile image
Ken Bellows

This is a very old school trick that is still useful on contexts like embedded development where you have very limited memory available.