Last Updated: October 07, 2020
· 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.

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…

over 1 year ago ·

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 ·

try this method of swapping without using a third variable


var a= 4;
var b= 2;


document.write("<br />");


over 1 year ago ·

In todays world, it gets even simpler:

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


over 1 year ago ·