How to swap two variables in JavaScript

Lukas picture Lukas · Apr 24, 2013 · Viewed 160.2k times · Source

I have this two variables:

var a = 1,
    b = 2;

My question is how to swap them? Only this variables, not any objects.

Answer

showdev picture showdev · Apr 24, 2013

Here's a one-liner to swap the values of two variables.
Given variables a and b:

b = [a, a = b][0];

Demonstration below:

var a=1,
    b=2,
    output=document.getElementById('output');

output.innerHTML="<p>Original: "+a+", "+b+"</p>";

b = [a, a = b][0];

output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>