1

I need some help with return and destructure an object from a function. I want to assign new paras to what ever return from the function.

function someRes() {
const val1 = 1
const val2 = 2
    return {val1, val2}
}

const {val1, val2} = someRes()
const {val3, val4} = someRes()//this returns as undefined

console.log(val1, val2)
console.log(val3, val4) //console.log undefined

I understand that destructure a params is not like assign them to new params but still, Im looking for an elegant way to do it.

thank!

0

2 Answers 2

4

You can use aliases during destructuring. When you use destructuring syntax, the variables created assumes the same name as the corresponding object properties. You can change that using the : while destructuring :

function someRes() {
  const val1 = 1
  const val2 = 2
  return {
    val1,
    val2
  }
}

const {
  val1,
  val2
} = someRes()
const {
  val1: val3,
  val2: val4
} = someRes() 

console.log(val1, val2)
console.log(val3, val4)

Sign up to request clarification or add additional context in comments.

Comments

3

someRes returns an object with two properties val1 and val2. Object destructuring requires that you access properties by name so {val3, val4} returns undefined because the object doesn't have those properties.

It looks like you might want to return a tuple instead of an object from your function. Array destructuring is by index so naming is not constrained by property name.

function someRes() {
  const val1 = 1;
  const val2 = 2;

  return [val1, val2];
}

const [val1, val2] = someRes();
const [val3, val4] = someRes();

console.log(val1, val2);
console.log(val3, val4);

Otherwise you can alias the second destructuring assignment as mentioned in the other answer

function someRes() {
  const val1 = 1;
  const val2 = 2;

  return {val1, val2};
}

const {val1, val2} = someRes();
const {val1: val3, val2: val4} = someRes();

console.log(val1, val2);
console.log(val3, val4);

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.