Home > Mobile >  Return returns undefined but console returns value
Return returns undefined but console returns value

Time:07-21

Algorithm for the recursive sum of all the digits in a number. Example: 942 --> 9 4 2 = 15 --> 1 5 = 6.

Could someone tell me why there is a correct sum in the console when i print it by console.log but when i want to return there is undefined?

let sum = 0;

const sumOfDigits = (num) => {
  let number = num.toString();

  if (number.length > 1) {
    sum = 0;
    [...number].forEach((digit) => {
      sum  = Number(digit);
    });
    sumOfDigits(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(sumOfDigits(942));

CodePudding user response:

You dont return the value for all the calls

Change sumOfDigits(sum); to return sumOfDigits(sum); like below

let sum = 0;

const sumOfDigits = (num) => {
  let number = num.toString();

  if (number.length > 1) {
    sum = 0;
    [...number].forEach((digit) => {
      sum  = Number(digit);
    });
    return sumOfDigits(sum);
  } else {
    console.log(sum);
    return sum;
  }
};

console.log(sumOfDigits(942));

  • Related