There is nothing wrong.
for(`INIT`;`TEST`;`ACTION`)
{
`WORK`;
}
The INIT
(initialization) can be done outside the loop.
var i=0;
for(;i<=100;i++)
//do something
The TEST
part yield a result that is either true
or false
. Now in this case value of i
is tested. Until it becomes zero this works.
The ACTION
part is generally used to change the loop variable. But you can leave it also or probably add it to the TEST
section like it is done here.
Look this examples are going to clear your idea
var i=0;
for( i++; i++; i+=j); //No body
var i=0;
for(;;); //an infinite loop
var i;
for(i=-4;i;i++);//
Even sometimes WORK
is placed in ACTION
.
Example:
factorial of x
for(var i=1,ans=1;i<=x;ans=ans*(i++));
Which can be written this way also-
var ans=1;
for(var i=1;i<=x;i++)
ans=ans*i;
NOTE: You can write whichever way you want. It doesn't matter as long as you have written the code properly. Get used to this kind of form you will see them a lot.
Though, it is better to write sometimes in compact form , but remember you should keep the readability.