0

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.

3
  • 1
    Why do you need this? Is it because of some (perceived) concurrency problem, or just for convenience? Commented Aug 15, 2018 at 11:47
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 15, 2018 at 11:48
  • @TimBiegeleisen Just conveniency. I have updated the question. Commented Aug 15, 2018 at 11:51

3 Answers 3

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if the variables have been declared before, for example class members?
Thank you! Great! It was difficult to google this.. Now I know it is called object destructuring.
3

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.