Search code examples
javascriptvariable-assignmentdestructuring

Assignment to Multiple Variables in JavaScript


Can properties of an object somehow be assigned to multiple variables in JavaScript with a single call (for convenience)?

function getValues() {
    return {
        first: 1,
        second: 2
    };
}

function convenientAssignment() {
    let first = 0;
    let second = 0;
    {first, second} = getValues(); // <-- How can this be achieved?
    console.log("Values:", first, second);
}

Without using separate assignments like the following:

let values = getValues();
first = values.first;
second = values.second;

This question has nothing to do with concurrency.


Solution

  • You were very close, Use object destructuring to get an objects values into variables.

    function simultaneous() {
        const {first, second} = getValues(); // <-- et voila!
        console.log("Values:", first, second);
    }
    

    In your example, where your variables were already declared, you can do:

    function convenientAssignment() {
        let first = 0;
        let second = 0;
        ({first, second} = getValues()); // <-- et voila!
        console.log("Values:", first, second);
    }