Swapping variables with JavaScript

Swapping the value of two variables normally takes three lines and a temporary variable. What if I told you there was an easier way to do this with JavaScript?

Traditional method

The goal is to swap the values of a and b. The textbook method for doing this looks something like this:

var a = 1, 
    b = 2, 
    c;

c = a;
a = b;
b = c;

Of course, we've introduced another variable called c to temporarily store the original value of a during the swap. But can we do it without c?

One-line method

This trick uses an array to perform the swap. Take a second to wrap your head around it:

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

There are a few things happening here, so if you're still having trouble understanding how or why this works, I'll explain:

  1. We're utilizing an array where the first index is the value of a and the second index is the value of  b
  2. a is set to the value of b when the array is created
  3. b is set to the first index of the array, which is  a
  4. MAGIC

While this trick definitely saves you a few lines of code and a temp variable, be cautious when using it. It's doesn't help that whole code clarity thing.

Want to learn another cool way to swap variables? If you're a math buff, you'll like the xor trick.

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.