DEV Community


Discussion on: Swap two numbers without using a temporary variable

michaelphipps profile image

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

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.

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.