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 !

4
  • 2
    JavaScript doesn't allow this kind of pattern matching. Commented May 27, 2013 at 7:24
  • This would be valid syntax in CoffeeScript, which turns this into: var _ref = [b, a], a = _ref[0], b = _ref[1]; Commented May 27, 2013 at 7:27
  • Pls see jsfiddle.net/sethunath/MqWKH Commented May 27, 2013 at 7:30
  • see this question: stackoverflow.com/questions/3709866/… Commented May 27, 2013 at 19:39

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe @Sethunath is just asking for an explanation of how it works. MDN has an article here: developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/…
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!

Comments

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.

2 Comments

@Sethunath look at the browser console, you can see the logged error there
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.