首页 > 解决方案 > Can someone explain how the routine below is logging "undefined" in console?

问题描述

Code snippet below suppose to log sum of digits in the given number.But, it returns undefined. Can someone please explain how it works under the hood?

const checkNumbers = (membershipId) => {
  if (membershipId.length === 1) {
    return membershipId;
  }
  if (membershipId.length > 1) {
    sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
    checkNumbers(sumOfNumbers.toString());
  }
};

console.log(checkNumbers("555"));

标签: javascript

解决方案


Because except for the length === 1 case, you don't have a return statement. If there's no return statement, then undefined is returned implicitly once the end of the function is reached.

To fix it, change this:

checkNumbers(sumOfNumbers.toString());

To this:

return checkNumbers(sumOfNumbers.toString());

Full code:

const checkNumbers = (membershipId) => {
  if (membershipId.length === 1) {
    return membershipId;
  }
  if (membershipId.length > 1) {
    sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
    return checkNumbers(sumOfNumbers.toString());
  }
};

console.log(checkNumbers('555'));


推荐阅读