Javascript for loop with iterator In the middle and decrement operator to the left of i?

For a non-recursive example of a factorial function, I found this example and am having difficulty keeping track of the code:

function fact(x) {
   if(x == 0) {
       return 1;
   }
   if(x < 0 ) {
       return undefined;
   }
   for(var i = x; --i; ) {
       x *= i;
   }
   return x;
}

      

I don't understand the syntax of this for loop: why shouldn't the iteration statement in the middle be where the test condition would normally be? Does this mean that there is no test condition or no iteration? Can you leave one or both of them?

Second, what's the difference what's in a for loop ++i

or --i

as opposed to i++

and i--

?

If I wanted to find fact(5)

, would there be i

4 or 5 in the first iteration of the for loop ?

+3


source to share


4 answers


In js, 0 means false and the rest of the values ​​are 1.

why is the iteration operator in the middle

for(var i = x; --i; /* optional */ )
               ^^ its decrement as well as the condition
                 loop continues until, i is 0

      

In fact, you can create an infinite loop



for(;;);

      

I wanted to find fact (5), in the first iteration of the for loop: Am I 4 or 5?

for(var i = x /* i=5 */; --i/* i=4 */; ) {
       x *= i;/* i=4 */
   }

      

+2


source


In JavaScript, 0

evaluates to false

. What is done here is to omit the iteration part of the loop and iterate over the test part. --i

first decrements the value i

by 1 and then the for loop evaluates it, only executing if it is not 0

.



+2


source


The difference between i--

and --i

is that it --i

first subtracts 1 from i and then evaluates i, and i--

first evaluates i and then subtracts 1 from i. eg:

var i=5;
console.log(i--);

      

will print 5

, and:

var i=5;
console.log(--i);

      

will print 4

.

+1


source


I think for

there is something wrong with the loop , as if you were trying to get the factorial

number you should stop decreasing the number when it reaches 2

. So the loop for

should be something like this

for(var i = x; i > 2;--i) {
    x *= i;
}

      

Also the first operator if

must be

if(x == 0 || x == 1) {
    return 1;
}

      

The difference between i--

and --i

is that

i--

decreases i

at the end of the loop iteration, and --i

decreases it before the start of the iteration.

So, on the first iteration, i

is 4

when you try to get fact(5)

.

0


source







All Articles