Although the type of the variable is correctly number, function keeps returning it undefined

Advertisements

purpose of this code is recursively sum the digits of a number. like;
473 -> 4+7+3 = 14 -> 1+4 = 5 and stop here. All of the functions seem to be working correct except, in the last function there is an if check to check if the number is below 10. inside the functions it console out the number and its type correct as denoted with comments but the return statement keeps returning undefined. what am I missing?

let digits = [];

function extractDigits(n) {
  const digit = n % 10;
  digits.push(digit);
  if (n >= 10) extractDigits((n - digit) / 10);
}

function digitalRoot(n) {
  extractDigits(n);
  const total = digits.reduce((acc, cur) => acc + cur, 0);
  digits = [];
  if (total < 10) {
    console.log(total); // this works without problem ---> 5
    console.log(typeof total); // this also works --- > number
    return total; // but returns undefined
  }
  digitalRoot(total);
}

console.log(digitalRoot(473));

>Solution :

The initial call to digitalRoot(n) does not have a return value, and it defaults to undefined.

To fix this issue, you should explicitly return the result of the recursive call:

let digits = [];

function extractDigits(n) {
  const digit = n % 10;
  digits.push(digit);
  if (n >= 10) extractDigits((n - digit) / 10);
}

function digitalRoot(n) {
  extractDigits(n);
  const total = digits.reduce((acc, cur) => acc + cur, 0);
  digits = [];
  if (total < 10) {
    console.log(total); // this works without problem ---> 5
    console.log(typeof total); // this also works --- > number
    return total;
  }
  return digitalRoot(total);// return the result of the recursive call
}

console.log(digitalRoot(473));

Leave a ReplyCancel reply