Other people gave good, correct answers, but I want to be clear about why , as this may not be obvious to some people (not aimed at the OP).
A function is nothing more than a set of steps for a computer.
This is called a function call:
getSmallestDivisor(121)
At any time, the return keyword is used, the function stops and replaces the function call with what comes after this returned word (this may be nothing).
So, in this case, the problem with the original function is that when the script reaches this line ...
getSmallestDivisor(xSqrt);
... it returns 11 to this function call, which never returns to the original function call that occurred inside alert() .
So the solution is simply to add return to where it calls itself.
return getSmallestDivisor(xSqrt);
This is a common mistake when creating recursive functions. A good way to help understand what is happening is to use the link extensively.
function getSmallestDivisor(xVal) { console.log("This is xVal: " + xVal); if (xVal % 2 === 0) { console.log("xVal % 2 === 0 was true"); return 2; } else if (xVal % 3 === 0) { console.log("xVal % 3 === 0 was true"); return 3; } else { console.log("This is else."); var xSqrt = Math.sqrt(xVal); console.log("This is xSqrt of xVal: " + xSqrt); if (xSqrt % 1 === 0) { console.log("xSqrt % 1 === 0 was true... recursing with xSqrt!!!"); getSmallestDivisor(xSqrt); } else { console.log("This is the else inside of else. I am returning: " + xVal); return xVal; } } } var y = getSmallestDivisor(121); console.log("This is y: " + y);
Now in your browser you can open the console (Option + Command + J on Chrome / Mac) and see what happens - what parts are executed, etc.
source share