How to swap two variables in JavaScript

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>

Leave a Comment