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 ?
source to share
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 */
}
source to share
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)
.
source to share