As far as I know “product” is the beginning point of the iteration (loop), from all exersizes and examples for loops have always taught that the loop starts at “product”. Now I’m very confused because if one puts this code into an editor it actually factorizes the number 5, I don’t see why it should
I got this example as one of the solutions here:
Please explain to me how…the value used to initialize is now suddenly used to show where the loop ends? lol
**Your code so far**
function factorialize(num) {
for (var product = 1; num > 0; num--) {
product *= num;
}
return product;
}
factorialize(5);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36
for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
1 - A for loop starts by invoking the initial expression.
2 -Before executing the statement, the loop checks the condition expression.
If true it executes the statement.
3 - After executing the statement, it will execute the increment expression.
Then back at checking the condition (2) and repeating those steps.
Let’s take the above function factorialize(5)
This is how it will unfold.
initial expression: product = 1
condition: 5 > 0 ? true → execute the statement → product = 5 * 1
(so now product is 5)
increment expression: num-- → num = 4
condition: 4 > 0 ? true → statement → product = 5*4
(so now product is 20)
increment: num-- → num = 3
[…so on and so forth]
Until num = 0.
Hope this makes better sense…
Kida difficult to explain it “visually”
function factorialize(num) {
for ( var product = 1; num > 0 ; num- -){
product *= num;
}
console.log(product);
}
factorialize(5)
// first cycle
// for (var product = 1; 5 > 0; num--) {
// product *= num; // for this cycle 5 is greater than
0 so output is product value is 1 and our
num value is 5 so output = 5
// second cycle
// 4 > 0 so cycle will contitnue output for this
cycle is 20 because of first cycle 5 * 4 and here
num = 4 because we are decreasing num–
// third cycle
// 3 > 0 output of third cycle will be 20 * 3 = 60
// fourth cycle
// 2 > 0 output 60 * 2 = 120
// fifth cycle
// 1 > 0 output of this cycle is 120 * 1 = 120
// sixth cycle
// 0 > 0 which is false so here loop will end
// that why output of our loop will be 120
The point im trying make here is…this loop ends at product, not start.
For example 1(“product” at beginning) 2345 (end of loop)
Not:
5432(“product” at end)1 (end of loop)
Look, its not the different variables thats involved, the way i understand this solution is that it uses the initiation variable to actually end the loop, as far as i know this is wrong?