Search code examples
javascriptvariablesswap

How to swap two variables in JavaScript


I have this two variables:

var a = 1,
    b = 2;

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


Solution

  • 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>";
    
    // swap values for variables "a" and "b"
    b = [a, a = b][0];
    
    output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
    <div id="output"></div>