2
 [a,b] = [b,a]

How does the above code swap a and b ?

I could see that the Right hand side of the expression crates an array, but I could not understand how it can be assigned to the left hand side.

Please see this fiddle http://jsfiddle.net/sethunath/MqWKH/

Update : Works only in firefox !

Sethunath K M
  • 4,702
  • 3
  • 28
  • 42

3 Answers3

4

JavaScript 1.7 adds destructuring assignment, which you're observing there. JavaScript 1.7 is supported by few browsers. Notably, however, it is supported by Mozilla Firefox when the script tag has a type attribute of application/javascript;version=1.7.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • Maybe @Sethunath is just asking for an explanation of how it works. MDN has an article here: https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Destructuring_assignment_%28Merge_into_own_page.2Fsection%29 – mzedeler May 27 '13 at 07:39
0

The above code doesn't swap a and b, it will give you an

Invalid left-hand side in assignment 

What do you want to do exactly? You can't, in Javascript, swap variables in this way!

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
0

Trying in browser:

[a,b] = [b,a]

Result:

ReferenceError: Invalid left-hand side in assignment

In other words: this isn't allowed in JavaScript.

CoffeeScript (which compiles to JavaScript) does, however.

mzedeler
  • 4,177
  • 4
  • 28
  • 41
  • @Sethunath look at the browser console, you can see the logged error there – Arun P Johny May 27 '13 at 07:30
  • I've learned something new today: what you are doing is going to be implemented in JavaScript version 1.7, but for obvious reasons, it may take very long time before you can expect it to work everywhere. – mzedeler May 27 '13 at 07:34