Swap values of two variables without using a temporary variable
The usual way to swap the values of two variables is usually somethign like this:
var temp = var1;
var1 =var2;
var2 = temp;
A nifty trick, how to change the values of two variables without using a temporary variable, is the following one liner:
b = [a, a = b][0];
It's nice, obfuscating what it does to someone new to JavaScript, and of course a good bit slower because of the array creation. But maybe someone else has a use for it.
Credits: I found this neat trick on stackoverflow.
Written by Georg
Related protips
4 Responses
Add your response
You replace a 3rd variable by an extra array?! What's the point?!
You've listed the caveats of such solution and still you promote it without explaining the benefits of it... (which doesn't exists IMHO), didn't understand your point...
try this method of swapping without using a third variable
<script>
var a= 4;
var b= 2;
a=a+b;
b=a-b;
a=a-b;
document.write("a","=",a);
document.write("<br />");
document.write("b","=",b);
</script>
In todays world, it gets even simpler:
var a = 4;
var b = 2;
[a, b] = [b, a]
:D