BaiLeiTao
BaiLeiTao

Reputation: 21

Javascript swap two objects a, b, which way is better?

Get 3 ways to swap two objects a and b in js, but not sure if there has any difference between them and which one is better?

1.

[a, b] = [b, a]

2.

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

3.

temp = a;
a = b;
b = temp;

Upvotes: 0

Views: 416

Answers (3)

Tushar Gupta
Tushar Gupta

Reputation: 15923

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

b = [a, a = b][0]; // shorthand version

ES6 (Firefox and Chrome already support it (Destructuring Assignment Array Matching)): But its extremely slow.

The temp variable method is slightly faster, and more general and more readable as well

Upvotes: 0

Jorjon
Jorjon

Reputation: 5434

IMO, better way would be:

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Source: Destructuring Assignment

Upvotes: 0

robertmain
robertmain

Reputation: 419

Define "better"...

Personally - for readability, I'd say the first example.

The second example I could probably follow if I had 2 or 3 whiteboards...the third example should be a capital offense ;)

Upvotes: 2

Related Questions