Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDavid Bison
2,838 PointsPlease help me understand how the for loop is working within this function.
Hello,
I am working on a for loop within a function, and I'm having trouble understanding why it returns a value of 1 at a certain point. Here is the code I'm working with:
function firstFactorial (num) { var factorial = num; for (var i = num - 1; i > 0; i--) { factorial = factorial * i; } return factorial; }
When I pass firstFactorial the number 1, it returns a value of 1. I am under the impression that firstFactorial(1) should return the value 0.
Specifically, inside the for loop, i = num - 1. Which means i should equal 0 when num is 1.
If you could help me with this, I would be very thankful.
1 Answer
Damien Watson
27,419 PointsHey David,
At the start, you set 'factorial = num', which means factorial is set to '1'. The for loop doesn't run because 'i' is set to '1-1' which equals '0' and the loop only runs if 'i' is > '0'.
Therefore factorial is still set to the original value of '1'.
function firstFactorial (num) {
var factorial = num;
for (var i = num - 1; i > 0; i--) {
factorial = factorial * i;
}
return factorial;
}
Damien Watson
27,419 PointsDamien Watson
27,419 PointsA further thought here, a factorial of '1' should return '1'. Because there is '1' way to organise '1'. An interesting fact is that a factorial of '0' should also return '1'.
Maybe prior to the return function, you should check if factorial is = '0' and change to '1'.
David Bison
2,838 PointsDavid Bison
2,838 PointsThank you, Damien, for the help. The suggestion for an if statement at the end is an excellent idea.