1

I would like to be able to do this kind of assignment in node js:

[a,b,c] = [1,2,3]

or just like in python

a,b,c = 1,2,3

so that I would have a=1, b=2 and b=3.

Actually the purpose of this is to do something like

[a,b,c] = somefunc()

or for array declaration

[a,b,c] = [[],[],[]]

Any ideas?

David
  • 929
  • 1
  • 11
  • 17

2 Answers2

5

"Node" isn't a language. You're really asking if you can do this in JavaScript, and no, you can't. There isn't any form of destructured assignment in JavaScript (prior to 1.7), and no way of making anything like that work. You cannot assign to an array.

Unless you're using JavaScript 1.7. Then it will work exactly as you've written it.

user229044
  • 232,980
  • 40
  • 330
  • 338
5

Not yet - Node.js uses V8 engine, which implements ECMA Script 5.

But this functionality will be avialable in the next, ECMA Script 6, release. It's described i.e. in this blog post or on this wiki. V8 (thus Node.js as well) will implement it, as per this issue.

Once it's implemented, it'll look like this:

[a, b] = [b, a]

or this:

function f() { return [1, 2, 3] }
var [a, , b] = f();

(examples from the wiki).


If you really need this, you can always use tools like Google Traceur compiler which allows you to write ES6 code and "compile" it into JavaScript compatible with all modern browsers (and Node.js).

kamituel
  • 34,606
  • 6
  • 81
  • 98