how to call the function inside itself in javascript?

Tags:



I am a beginner in JavaScript and I faced this test on one of testing websites and they gave me this test which is a function that convert given number to checkId which is the sum of all digits of the given number for example: given 237 its 2+3+7=12 12 is 1+2= 3 so the returned value should be 3 this is my code and the problem it gives me UNDEFINED please help thank you

function createCheckDigit(membershipId) {
  if (membershipId < 10) {
    return membershipId;
  } else {
    var digits = ("" + membershipId).split("");
    for (var i = 0; i < digits.length; i++) {
      digits[i] = parseInt(digits[i]);
    }
    var res = digits.reduce((a, b) => a + b, 0);
    // recursion 
    createCheckDigit(res);
  }
}
document.write(createCheckDigit("450"));

Answer

You were just missing to return the result of the inner call :

function createCheckDigit(membershipId) {
  if (membershipId < 10) {
    return membershipId;
  } else {
    var digits = ("" + membershipId).split("");
    for (var i = 0; i < digits.length; i++) {
      digits[i] = parseInt(digits[i]);
    }
    var res = digits.reduce((a, b) => a + b, 0);
    // missing return here 
    return createCheckDigit(res);
  }
}
document.write( "450 => "+createCheckDigit("450"));
document.write( "<br>730 => "+createCheckDigit("730"));
document.write( "<br>480 => "+createCheckDigit("480"));


Source: stackoverflow