Tell us what’s happening:
How does this code work?
Your code so far
function factorialize(num) {
let n = 1;
while(num >= 1){
n = n * num;
num--;
}
num = n;
return num;
}
factorialize(5);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number
So if num
is 5. Set a counter (n
) to 1. Then loop num
downwards from 5, setting the counter to its current value * num
on each iteration. So
n == 1, num == 5
num >= 1, so
n = 1 * 5
n == 5, num == 4
num >= 1, so
n = 5 * 4
n == 20, num == 3
num >= 1, so
n = 20 * 3
n == 60, num == 2
num >= 1, so
n = 60 * 2
n == 120, num == 1
num >= 1, so
n = 120 * 1
n == 120, num == 0
num is not >= 1, so set num
num = 120
return num
The reason the counter n
is set at 1 is that if 0 is passed, the while loop won’t start, and num will be set to 1, and returned (the factorial of 0 is 1)