For (;;) loop description

In JS, I came across a type loop for(;;)that functions like a loop while(true). What do the semicolons in parentheses of this loop mean?

+4
source share
6 answers
for (statement 1; statement 2; statement 3) {
    code block to be executed
}

Statement 1 is optional and runs before the start of the loop (code block).

var i = 0;
var length = 10
for (; i < length; i++) { 

    //The for loop run until i is less than length and you incerement i by 1 each time. javascript doesnt care what you do inside, it just check whether you have variable with name i and length
}

Statement 2 again optionally defines a condition for starting a loop (code block).

var i = 0;
var len = 100;
for (i = 5; ; i++) { 
    //Here you are just initializing i with 5 and increment it by 1 there is no break condition so this will lead to an infinite loop hence we should always have a break here somehwere.
}

Operator 3 is optional and is executed every time after the execution of the cycle (code block).

var i = 0;
var length = 100;
for (; i < length; ) { 
    //Here you are just checking for i < length which is true. If you don't increment i or have an break it will turn into infinite loop
}

In a walnut shell, when you have no conditions or initialization, it turns into an endless cycle.

+7
source

Typically, the for loop header contains 3 parts:

for (var i = 0 ; i < 10 ; i++)
//   ^^^^^^^^^   ^^^^^^   ^^^

, , , , , i.

, , for . , . , . , .

, for(;;) - , . , .

+4

( )

+3
for ( init; condition; increment )
{
   statement(s);
}

for:

init . . , .

. , . , , for.

, for , increment. . , .

. , , ( , , ). , , for .

+3

for :

for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
}

, :

for(; true ;)
{ }

.

+3

, . for :

for (i = 0; i < 10; i++)

for (;;)

, .

+1

Source: https://habr.com/ru/post/1678977/


All Articles