javascripttuplesdestructuring

Is it possible in JavaScript to simultaneously assign to multiple variables like it is in Python?


In some languages, like Python, you can define and assign values to a tuple of variables, and retrieve their values like this:

name, age = ("Bob", 24)
print(name)           # name evaluates to "Bob"
print(age)            # age evaluates to 24

Is there anything similar in JavaScript? Or do I just have to do it the ugly way with an array:

tuple = ["Bob", 24];
name = tuple[0];      // name Evaluates to Bob
age = tuple[1];       // age Evaluates to 24

Is there a better way to simulate Python tuples in JavaScript?


Solution

  • JavaScript 1.7 added destructuring assignment syntax which allows you to do essentially what you are after:

    function getTuple(){
       return ["Bob", 24];
    }
    var [a, b] = getTuple();
    // a === "bob" , b === 24 are both true