Snackoverflow
Snackoverflow

Reputation: 6271

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.

Upvotes: 0

Views: 94

Answers (3)

conradj
conradj

Reputation: 2610

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);
}

Upvotes: 3

Strelok
Strelok

Reputation: 51441

In your particular case since you've already declared first and second you need to wrap the descructuring assignment in brackets () like so:

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

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

Because {first, second} by itself is considered a block.

Upvotes: 1

Sirko
Sirko

Reputation: 74036

This is pretty much what a destructuring assignment is supposed to do:

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

let { first, second } = getValues();

console.log( first, second );
// 1 2

Upvotes: 3

Related Questions