Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 312
dreamkiller Avatar asked Sep 09 '26 15:09

dreamkiller


2 Answers

the second part of your for loop is the Condition:

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

Once --i reaches 0, it evaluates to false (falsey) and the for "exits"

adding a console.log(i) to your for loop will help demonstrate that

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

like image 126
Luca Avatar answered Sep 12 '26 05:09

Luca


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.

like image 42
Robby Cornelissen Avatar answered Sep 12 '26 04:09

Robby Cornelissen