0xnuva
Last Updated: April 27, 2017
·
4.773K
· calamari

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.

5 Responses
Add your response

10735

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

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

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>

over 1 year ago ·
28873

In todays world, it gets even simpler:

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

:D

over 1 year ago ·