0xnuva
Last Updated: April 27, 2017
·
2.756K
· calamari
6b4b7f11163b1e87571995ce8c3f0bce

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.

Say Thanks
Respond

5 Responses
Add your response

10735
3eae340e049abecfb4a117ad7a907bd1

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…

over 1 year ago ·
10736
6b4b7f11163b1e87571995ce8c3f0bce

There is none. At least not in the traditional (or good way) of coding. If you start golfing your code (maybe for some 140bytes competition, that neat little trick can be of use.

And some people like to have a concise solution.

But basically I was like sharing that. ;-)

over 1 year ago ·
10739
User

The first element of the array takes part of a temporary variable. I mean you're implicitly making a temporary variable (despite the title.)

over 1 year ago ·
28332

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>

6 months ago ·
28873
6b4b7f11163b1e87571995ce8c3f0bce

In todays world, it gets even simpler:

var a = 4;
var b = 2;
[a, b] = [b, a]

:D

about 1 month ago ·