let x = 5, y = 3;
x = x + y;
y = x - y;
x = x - y;
console.log(x, y); // 3 5
Enter fullscreen mode
Exit fullscreen mode
...
For further actions, you may consider blocking this person and/or reporting abuse
isn't there a more clever way to do this?
There certainly is. The way in the post only works for numbers and not even very large numbers (the sum of a + b has to be less than MAX_SAFE_INTEGER) but applying the destructuring assignment is the simplest and cleanest way in my opinion.
let a = 1;
let b = 2;
[a, b] = [b, a];
a; // => 2
b; // => 1
Not to be negative, but something like this would never be used in production code because the overhead of constructing arrays will be significantly larger than the standard approach of a temp variable.
It's more important that the CPU do less work than to save a line of code. Also, in general 10 lines of simple to read code is always preferable to 1 line of more complex to read code, all other things being equal. Some developers get concerned with counting lines of code, and that's not what matters.
I disagree, this code is highly readable. In fact, you'll feel right at home if you come from python world. The following piece of code to swap 2 variables is consider pythonic:
If you're worry allocating a temporary array causing performance issue, then you should stay away from JavaScript in the first place
The temporary array is most likely optimized away.
That's almost certain, iirc most of the array related code are written C++, at least for Chrome's V8 anyway
Great post. Cool trick! Thanks for introducing me to codedrops.tech!
Serious question though - why would you avoid using the temporary variable?
Just about the same number of characters, more clear what is being done.
This is a very old school trick that is still useful on contexts like embedded development where you have very limited memory available.
I too feel it has no real-world application. Limited memory would be possible when used in Embedded Systems. And I feel this is more of a logical question.