Javascript for unexpected loop behavior

I have a couple of questions about the javascript for loop.

First question:

for (i=0; i<=2; i++) {;} console.log(i); 

The output is 3. Shouldn't it be 2?

Second question:

 for (var i=0; i<=2; i++) { setTimeout(function(){console.log(i);}, i*1000); } 

The timeouts are set correctly: 0, 1000 and 2000. But the output is 3.3.3 (should be 0, 1, 2). Does this mean that deferred functions are executed after the loop ends? What for?

What should I read to understand all these cryptic javascript?

Thanks.

+4
source share
2 answers

First question:

No, since the variable i increases after the last successful iteration, then the condition is checked and evaluated as false , so the loop ends.

The for statement consists of:

 for ([initialExpression]; [condition]; [incrementExpression]) statement 

And it is executed in the following steps:

  • initialExpression is evaluated at the beginning
  • The condition evaluated, if it is evaluated as false , the cycle ends, if it is evaluated as true , the operator is evaluated.
  • Calculate the statement.
  • Evaluated incrementExpression , go to step 2.

Second question:

The function is executed asynchronously after , the cycle has ended, at this time, as you know, i contains 3 .

A common workaround for this is to use a function to store the value of a loop variable for each iteration, for example:

 for (var i=0; i<=2; i++) { (function (i) { setTimeout(function(){console.log(i);}, i*1000); })(i); } 
+10
source

This is because your console.log command is outside the for loop.

This will print up to two as you planned:

 for (i=0; i<=2; i++) { console.log(i); } 

For loops, only what you enter in parentheses will be repeated. This is why console.log was executed only once.

Source: http://www.kompulsa.com/a-guide-to-for-loops-in-javascript/

0
source

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


All Articles