Callum Hussell Callum Hussell - 4 months ago 7
Javascript Question

JavaScript - Factorialization 'For Loop' Understanding?

I am in the midst of completing some JavaScript algorithmic challenges and I had to factorialize a number as part of one of them. After searching through stack and other places I entered a correct code block:

function factorialize(num) {

if(num === 0) {
return 1;
}

if(num < 0 ) {
return undefined;
}

for(var i = num; --i; ) {
num *= i;
}
return num;
}

factorialize(5);


It it returns a correct result. What I am struggling to understand however is why the for loop doesn't have a second statement, and why it can run for ever? I have an inkling it's because as soon as
i
value is
0
, any subsequent negative number that is generated will be multiplied by 0 and so only the integer numbers will form the result. But why does the function return a valid number, if the loop is still running to -infinity and hasn't been told to stop when reaching a certain value?

Answer

All elements in a for-loop's expression are optional.

The second part of the for-loop is used to express the for-loop's condition. The condition is evaluated on every iteration, and when it evaluates to false, the loop is exited.

In this case, that second part that expresses the condition is --i. This means that on every iteration, i will be decremented by 1, until it finally reaches zero (0). Since 0 is considered to be a falsey value in Javascript, the loop exits.

Comments