javascriptrecursion

Why does console.log report the value of my variable, but return doesn't?


I'm working through a coding interview practice question. The prompt:

A company assigns each customer a membership ID, and you are implementing a check digit for those IDs.

The check digit should be calculated by adding up all digits in each membership ID. If the result of the sum is a number with more than a single digit, another iteration is required, and the digits of the result also should be added together. This process should repeat until a single-digit number is calculated.

Example: for membership ID '55555', the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result would be 7, which is the check digit.

So I'm attempting a recursive strategy for this. I seem to have been able to get the correct answer for a variety of queries, but I can't understand why my return in my base case is returning undefined, but the console.log just above it returns the correct value of 7. Thoughts?

function createCheckDigit(membershipId) {
  // Write the code that goes here.
  let checkDigit = membershipId;
  if ([...checkDigit].length === 1) {
    console.log(checkDigit); // this prints 7
    return checkDigit; // why doesn't this return 7?
  } else {
    let mIdList = [...checkDigit];
    sum = 0;
    for (let c in mIdList) {
      sum += Number(mIdList[c]);
    }
    createCheckDigit(sum.toString());
  };
}

console.log(createCheckDigit("55555"));

Solution

  • You need add return on your recursive call

    function createCheckDigit(membershipId) {
      // Write the code that goes here.
      let checkDigit = membershipId;
      if ([...checkDigit].length === 1) {
        console.log(checkDigit); // this prints 7
        return checkDigit; // why doesn't this return 7?
      } else {
        let mIdList = [...checkDigit];
        sum = 0;
        for (let c in mIdList) {
          sum += Number(mIdList[c]);
        }
        // line below altered to return results of recursive call
        return createCheckDigit(sum.toString());
      };
    }
    
    console.log(createCheckDigit("55555"));