i am trying to try factorial function but thewindow keeps loading without stop so i guess it turned into infinite loop i just don’t know why here is my code and the what i think is happening
ps i know i still need with 0 and 1 but i will write the if statement later i just started with the for loop
function fac(a) {
for (let i = 1; i < a; i++) {
a *= i;
}
return a;
}
console.log(fac(5));
/*
a let i = 1 a *= i i++ i < a?
1st iteration: 5 1 5 = 5 * 1 2 yes 2 < 5
2nd iteration: 5 2 10 = 5 * 2 3 yes 3 < 5
3rd iteration: 10 3 30 = 10 * 3 4 yes 4 < 5
4th iteration: 30 4 120 = 30 * 4 5 no
End of the FOR loop
*/
i looked online for a way to do it i found one in an article on freecodecamp
https://www.freecodecamp.org/news/how-to-factorialize-a-number-in-javascript-9263c89a4b38/
i just don’t why it works descending but not ascending here is the code
function factorialize(num) {
// If num = 0 OR num = 1, the factorial will return 1
if (num === 0 || num === 1)
return 1;
// We start the FOR loop with i = 4
// We decrement i after each iteration
for (var i = num - 1; i >= 1; i--) {
// We store the value of num at each iteration
num = num * i; // or num *= i;
/*
num var i = num - 1 num *= i i-- i >= 1?
1st iteration: 5 4 = 5 - 1 20 = 5 * 4 3 yes
2nd iteration: 20 3 = 4 - 1 60 = 20 * 3 2 yes
3rd iteration: 60 2 = 3 - 1 120 = 60 * 2 1 yes
4th iteration: 120 1 = 2 - 1 120 = 120 * 1 0 no
5th iteration: 120 0 120
End of the FOR loop
*/
}
return num; //120
}
factorialize(5);
my best guess is the a in i < a keep getting updated from inside the loop every loop and it doesn’t keep useing the initial value passed in the function but gets updates with a inside the function 10, 30 why. when num in var i = num -1 doesn’t get updated it keep using the initial value without the num inside the loop 20 , 60 , 120 affecting it both variable are in the expressions while one updates from the body and the other doesn’t it keeps updating from the initial value