Skip to content Skip to sidebar Skip to footer

How Does [b][b = A,0] Swap Between A And B?

As gdoron pointed out, var a = 'a'; var b = 'b'; a = [b][b = a,0]; Will swap a and b, and although it looks a bit of hacky, it has triggered my curiosity and I am very curious a

Solution 1:

var a = "a";
var b = "b";

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

Let's break the last line into pieces:

[b]       // Puts b in an array - a safe place for the swap.
[b = a]   // Assign a in b
[b = a,0] // Assign a in b and return the later expression - 0 with the comma operator.

so finally it is a =[b][0] - the first object in the [b] array => b assigned to a

Live DEMO

read @am not I am comments in this question:
When is the comma operator useful?
It's his code...


Solution 2:

It might help (or hinder) to think of it terms of the semantically equivalent lambda construction (here, parameter c takes the place of element 0):

a = (function(c) { b = a; return c; })(b);

Post a Comment for "How Does [b][b = A,0] Swap Between A And B?"