0

I was just tweaking some code in JS and ended up writing the below code.

const adding=(a,b,c,d)=> {
  return(a+b, c+d)
}

let sum1, sum2 = adding(1,2,3,4)
console.log(sum1)
console.log(sum2)

The output was Undefined 7

And when I changed the position of return values like below

const adding=(a,b,c,d)=> {
  return(c+d, a+b)
}

let sum1, sum2 = adding(1,2,3,4)
console.log(sum1)
console.log(sum2)

The out put was Undefined 3

My question is Why?

0

2 Answers 2

2

Your approach returns only the last expression, because of the comma operator and parentheses is not a valid data type, just a grouping operator ().

Instead you could take an array as data structure with further destructuring.

const adding = (a, b, c, d) => [c + d, a + b];

let [sum1, sum2] = adding(1, 2, 3, 4);
console.log(sum1)
console.log(sum2)

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

1 Comment

Thank you, It makes sense. I thought of comma as a separator but forgot it is an operator too.
0

In javascript, you can declare multiple variables on a single line separated with comma. Therefore you declared sum1 and sum2. However, you assigned value to only sum2

What you did is same as

let sum1;
let sum2 = add(1, 2, 3, 4);

2 Comments

But why the second return value is assigned to sum2, not the first return value.
Now I know why sum1 is undefined, Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.