Execution or not of the increment in loops for [closed]

1

Code 1 :

var x = 1; 
  
for( ; x<6 ; x+=2 ){ 
    x=x*x; 
} 

console.log(x);

In the above code even if the condition is false the part that increments is executed the last time.

Code 2:

 var x = 0; 

for( ; x<8 ; x++ ){} 
console.log(x); 

for( ; x>4 ; x-=2 ){} 
console.log(x); 

In the code above even if the condition is false the part that increments is not executed.

Why is this happening or am I making someone else an error?

    
asked by anonymous 19.10.2017 / 18:54

3 answers

4

In the first part he enters the for with x = 1 and makes x = x * xe of 1, then enters with x = 3 and makes x = x * x that of 9, this occurs inside the loop, now it comes out of the loop and makes x + = 2 then x = 11, back to see if x < 6 of false and printa 11;

Same logic in the second.

It's more or less like this:

x = 1 x < 6? true x = x * x x = 1 x += 2 x = 3 x < 6? true x = x * x x = 9 x += 2 x = 11 x < 6? false

    
19.10.2017 / 19:34
5

Dear For works the same in both cases, the problem is that your comparison was failed because in one place you started with 0 and in the other with 1 .

Except initialization For increments before comparing.

Soeven9beinggreaterthan6itwillstillincrement2andthencompare.

Seetheexamplebelowshowingstepbystep:

var x = 1; 
for( ; x<6 ; x+=2 ){ 
    x=x*x; 
    console.log('x:' + x);
} 
console.log('Final x:' + x);

var y = 1; 
for( ; y<8 ; y++ ){
  console.log('y: ' + y); 
} 
console.log('Final y: ' + y); 
    
19.10.2017 / 20:09
1

Although the instruction about the increment comes at the beginning of the for loop, you can consider that this increment actually runs just after the body of the loop, before the next check on the stop condition. So:

for(var i=0; i<10; i++) {
   // corpo do loop

   // incremento executado aqui
   // sai do loop com i === 10
}

Now, if the stop condition is false from the start, neither the loop body nor the increment will be executed:

var i = 10;
for( ; i<10; i++) {
    // nunca executa nem o corpo nem o incremento
}
// aqui, ainda temos i === 10
    
19.10.2017 / 20:15