How To Return Two Values In The Same Function

I was wondering how I could return these two values (totalPositive and newArr) in the same function. I want to return the array and then modify it (add all the values together and return that value). Here’s my code:

function sumDigits(num) {
  var newArr = []
  var stringifiedNum = num.toString()
  for (var i = 0; i < stringifiedNum.length; i++) {
    newArr.push(stringifiedNum[i])
  }

return newArr

var totalPositive = 0
for (var i = 0; i < newArr.length; i++) {
  totalPositive += newArr[i]
}
// return totalPositive?
 }

var outputPositive = sumDigits(1148);
console.log(outputPositive); // --> 14

If you want to pass out two values, then you need to pass them out in an array.

also remember that once a return value is executed the function stops, so anything you put after a return statement, it is not reached

2 Likes

Using an object is a fairly common way to return multiple values out of a function. But as said, an array would work as well.

function addAndSubtract(num1, num2) {

  let addition = num1 + num2;
  let subtraction = num1 - num2;

  return {
    addition,
    subtraction,
  };
}

const resObj = addAndSubtract(2,2)
const { addition, subtraction } = resObj

console.log(resObj); // { addition: 4, subtraction: 0 }
console.log(addition); // 4
console.log(subtraction); // 0
1 Like