How to assign multiple variables at once in JavaScript?

mlibre picture mlibre · Jul 16, 2016 · Viewed 19.2k times · Source

Is there any way to perform multiple assignment in JavaScript like this:

var a, b = "one", "two";

which would be equivalent to this:

var a = "one";
var b = "two";

Answer

Piyush.kapoor picture Piyush.kapoor · Jul 16, 2016

In ES6 you can do it this way:

var [a, b] = ["one", "two"];

The above code is ES6 notation and is called array destructuring/object destructuring (if it's an object).

You provide the array on the right-hand side of the expression and you have comma-separated variables surrounded by square brackets on the left-hand side.

The first variable maps to the first array value and so on.