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?

LoneWolf
  • 119
  • 1
  • 11

2 Answers2

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)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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);
Wakeel
  • 4,272
  • 2
  • 13
  • 14