[javascript] 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.

This question is related to javascript variables swap

The answer is


You can now finally do:

_x000D_
_x000D_
let a = 5;
let b = 10;

[a, b] = [b, a]; // ES6

console.log(a, b);
_x000D_
_x000D_
_x000D_


We can use the IIFE to swap two value without extra parameter

_x000D_
_x000D_
var a = 5, b =8;_x000D_
b = (function(a){ _x000D_
    return a _x000D_
}(a, a=b));_x000D_
_x000D_
document.write("a: " + a+ "  b:  "+ b);
_x000D_
_x000D_
_x000D_


In ES6 now there is destructuring assignment and you can do:

let a = 1;
let b = 2;
[b, a] = [a, b]  // a = 2, b = 1

ES6+ method: Since ES6, you can swap variables more elegantly. You can use destructuring assignment array matching. It’s simply. var a=10 b=20;

[a, b] = [b, a]

console.log(a,b) // 20 10


ES6 Destructuring:

Using an array: [a, b] = [b, a]; // my favorite

Using an object: {a, b} = {a:b, b:a}; // not bad neither


Here's a one-liner, assuming a and b exist already and have values needing to be swapped:

var c=a, a=b, b=c;

As @Kay mentioned, this actually performs better than the array way (almost 2x as fast).


How could we miss these classic oneliners

var a = 1, b = 2
a = ({a:b, _:(b=a)}).a;

And

var a = 1, b = 2
a = (_=b,b=a,_);

The last one exposes global variable '_' but that should not matter as typical javascript convention is to use it as 'dont care' variable.


Till ES5, to swap two numbers, you have to create a temp variable and then swap it. But in ES6, its very easy to swap two numbers using array destructuring. See example.

let x,y;
[x,y]=[2,3];
console.log(x,y);      // return 2,3

[x,y]=[y,x];
console.log(x,y);      // return 3,2

Since ES6, you can also swap variables more elegantly:

var a = 1,
    b = 2;

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

console.log('a:', a, 'b:', b); // a: 2 b: 1

Swap using Bitwise

let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;

Single line Swap "using Array"

[a, b] = [b, a]

You could use a temporary swap variable or XOR.

a = a ^ b
b = a ^ b
a = a ^ b

This is just a basic logical concept and works in every language that supports XOR operation.

edit: see the Comments. Forgot to tell that this works for sure only with integer. Assumed the integer variables from question's thread


You can use ES6 destructuring assignment like so:

let a = 10;
let b = 20;

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

console.log(a, b); // a = 20, b = 10

ES6 (Firefox and Chrome already support it (Destructuring Assignment Array Matching)):

_x000D_
_x000D_
let a = 5, b = 6;_x000D_
[a, b] = [b, a];_x000D_
console.log(`${a} ${b}`);
_x000D_
_x000D_
_x000D_


ES6 array destructuring is used to swap two variables. See example

var [x,y]=[1,2];
[x,y]=[y,x];

Easier way possible with :

x === 1 and y === 2; But after destructuring, x is y, i.e. 2, and y is x, i.e. 1.


As your question was precious "Only this variables, not any objects. ", the answer will be also precious:

var a = 1, b = 2

a=a+b;
b=a-b;
a=a-b;

it's a trick

And as Rodrigo Assis said, it "can be shorter "

 b=a+(a=b)-b;

Demo: http://jsfiddle.net/abdennour/2jJQ2/


Destructing assignment is the best way to solve your problem.

_x000D_
_x000D_
var a = 1;
var b = 2;

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

console.log("After swap a =", a, " and b =", b);
_x000D_
_x000D_
_x000D_


var a = 5;
var b = 10;

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

//or
b = [a, b];
a = b[1];
b = b[0];


alert("a=" + a + ',' + "b=" + b);

remove or comment the 2 //or's and run with the one set of code

http://jsfiddle.net/USdv8/57/


Single line swapping

a = a^b^(b^=(a^b));

(function(A, B){ b=A; a=B; })(parseInt(a), parseInt(b));


You can do this:

var a = 1,
    b = 2,
    tmp;
tmp = a;
a = b;
b = tmp;

For readability and maintainability, this can't be beat (at least in JavaScript). Anybody maintaining the code (including you six months from now) will know exactly what's going on.

Since these are integers, you can also use any number of clever tricks1 to swap without using a third variable. For instance you can use the bitwise xor operator:

_x000D_
_x000D_
let a = 1, b = 2;_x000D_
a = a ^ b;_x000D_
b = a ^ b;_x000D_
a = a ^ b;_x000D_
    _x000D_
console.log('a is now:', a);_x000D_
console.log('b is now:', b);
_x000D_
_x000D_
_x000D_

This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article.

1"The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague." — Edsger W. Dijkstra


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

a more verbose approach would be

let a = 2, b = 4;
a = [a, b];
b = a[0];
a = a[1];

It's very simple, use the ES6 array destructuring syntax which is [y, x] = [x, y] for more information consult this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment


Don't use the code below. It is not the recommended way to swap the values of two variables (simply use a temporary variable for that). It just shows a JavaScript trick.

This solution uses no temporary variables, no arrays, only one addition, and it's fast. In fact, it is sometimes faster than a temporary variable on several platforms.
It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.

a = b + (b=a, 0)

It works in two steps:

  • (b=a, 0) sets b to the old value of a and yields 0
  • a = b + 0 sets a to the old value of b

Because I hear this method runs slower:

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

If you plan on storing your vars in an object (or array), this function should work:

function swapVars(obj, var1, var2){
    let temp = obj[var1];
    obj[var1] = obj[var2];
    obj[var2] = temp;
}

Usage:

let test = {a: 'test 1', b: 'test 2'};

console.log(test); //output: {a: 'test 1', b: 'test 2'}

swapVars(test, 'a', 'b');

console.log(test); //output: {a: 'test 2', b: 'test 1'}

I see kind of programming olympiad here. One more tricky one-line solution:

b = (function(){ a=b; return arguments[0]; })(a);

Fiddle: http://jsfiddle.net/cherniv/4q226/


We are able to swap var like this :

var val1 =  117,
    val2 = 327;

val2 = val1-val2; 
console.log(val2);
val1 = val1-val2;
console.log(val1);
val2 = val1+val2;
console.log(val2);

Use a third variable like this:

var a = 1,
    b = 2,
    c = a;

a = b; // must be first or a and b end up being both 1
b = c;

DEMO - Using a third variable



Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to swap

How to swap two variables in JavaScript Is there a standardized method to swap two variables in Python? C++ trying to swap values in a vector Replace Div with another Div How to write a basic swap function in Java Java method to swap primitives convert big endian to little endian in C [without using provided func] Swap two items in List<T> How to swap String characters in Java? Swap two variables without using a temporary variable