Search code examples
javascriptmultiple-assignment

How to assign multiple variables at once in JavaScript?


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";

Solution

  • 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.