This is the function I am currently working on:
function getSmallestDivisor(xVal) {
if (xVal % 2 === 0) {
return 2;
} else if (xVal % 3 === 0) {
return 3;
} else {
var xSqrt = Math.sqrt(xVal);
if (xSqrt % 1 === 0) {
getSmallestDivisor(xSqrt);
} else {
return xVal;
}
}
}
alert(getSmallestDivisor(121));
I had designed the above function to return the lowest divisor of an integer. Consider the case 121
. It should actually return 11
in the current context. But it is returning undefined
.
I have checked how many times the recursive calls happened; they actually happened two times. I logged the values of xVal
in those two different calls, and they display 121
and 11
. I am really confused here about why this function is currently returning undefined
.
I've created a jsfiddle demo.
See Question&Answers more detail:os