4

I do not know how to learn demo 2,because it's difficult for me.

//demo1.js
var a = 1;
var b = 2;
var c;

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

log(a);   // a = 2
log(b);   // b = 1   I can read this one.


//demo 2.js

var a = 1, b = 2;
a = [b][b = a, 0];   // why? '0' is a varible?
console.log(a,b) //output a = 2, b =1
Ryan Yiada
  • 4,739
  • 4
  • 18
  • 20
  • Although this is neat, please do not learn this as something you should ever actually do. It is not quality code. – 000 Mar 26 '13 at 05:22

2 Answers2

2
//   v---- 1.  v---- 3.
a = [b][b = a, 0];
//      ^---^-- 2.
  1. Put the value of the b variable in a new Array.

  2. The next set of square brackets is the member operator used for getting the index. In this case, that space is being used to reassign the value of the a variable to the b variable. This can be done because the original value of b is safely in the Array (from step 1.).

  3. Separated by comma operator, the 0 index is then used as the actual value of the Array being retrieved, which if you'll recall is the original b value. This is then assigned to a via the first = assignment on the line.

So to summarize, b is put in the Array, and is retrieved via the 0 index and assigned to a on the left, but not before a is assigned to b (borrowing the space of the [] member operator).


This could also be written like this:

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

Only difference now is that the second index of the Array is used to do the assignment. Probably a little clearer like this.

0

The comma operator in Javascript evaluates its left operand, throws it away and returns its right operand after evaluating. Its only use is when the left operand has a side-effect (like modifying a variable's value) but you don't want its result.

[b] defines an array containing b.

[b = a, 0] evaluates b = a - so b now contains the value of a. Then it throws it away. Then it takes the element at index 0 of [b] - returning b. a now contains the value of b that was stored there, rather than the up-to-date value of b, so our swap is successful (albeit obfuscated).

Patashu
  • 21,443
  • 3
  • 45
  • 53