7

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 at how it works. It doesn't make any sense to me.

Community
  • 1
  • 1
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 2
    _"a bit of hacky"_??? a lot of hacky... :-) – gdoron Mar 25 '12 at 21:59
  • Relevant: [What's a better way to swap two argument values?](http://stackoverflow.com/questions/8482402/whats-a-better-way-to-swap-two-argument-values) – Šime Vidas Mar 25 '12 at 22:05
  • Wouldn't it have made more sense to comment on godron's other answer and ask for clarification in your original question? – Felix Kling Mar 25 '12 at 22:36
  • 1
    @FelixKling. I suggested him to ask it in other question. comments are not the place of questions-answers. And it's not just clarification of the answer, it's totally different question (In my humble opinion!) – gdoron Mar 25 '12 at 23:00

2 Answers2

9
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...

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
1

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);
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365