I've created a loop in JS to calculate factorials - however, instead of getting the factorial, I'm just only getting the first value of the for loop. In the code below, I'm just getting 1 for show(FirstFactorial(5));
Any ideas on what's wrong here...?
function FirstFactorial (num) {
var myVar=1;
for(var i=1; i<=num; i++){
myVar=myVar*i;
return myVar;
}
};
show(FirstFactorial(5));
Your loop actually returns when it first reaches the
return
and never runs after. This is how return works, returning back to where it was called. You would be better to place your return to run AFTER the loop has completed.Here is a JSFiddle of the result.
By using recursion, you can achieve much smaller code and eliminate the need for a
for loop
:Returns:
jsFiddle: http://jsfiddle.net/DuLpr/2/
You need to have your return statement outside of the loop:
Take the return statement outside of your for loop: