Instructions that depend on variables coming from "for" loop, need to be executed in callback?

2

For example:

var soma = 0;
for(var i = 0; i < 100; i++){
     soma += i;
}

if(soma < 500){
   console.log('Soma é menor que 500');
}
Since the if condition depends on the variable b , which comes from the for loop, the if conditional will only be executed when the loop for is complete, or do I have to put if on some kind of callback?

In short: I want to know if the browser "skips" for before it finishes, or if I can trust that the function / statement below for will only run when it is completed .

    
asked by anonymous 01.03.2017 / 10:46

1 answer

4

Yes, you can trust, for the case that you presented the browser does not "jump" the for and if will only be executed when it finishes, it simply does not enter your condition because the soma > 500 , 4950 in this case:

first 5 loops:

  

sum (0) + = 0 for sum (0) + = 1 for sum (1) + = 2 for sum (3) + = 3 for sum (6) + = 4

where at the end of these our sum will be 10 , hence for 100 loops it will be 4950 and will not enter our condition of being less than 500

var soma = 0;
for(var i = 0; i < 100; i++){
    soma += i;
}

console.log(soma);
if(soma < 500){
   console.log('Soma é menor que 500');
}

Here is an example with 200000000 (may take a while to finish executing):

var soma = 0;
for(var i = 0; i < 200000000; i++){
    soma += i;
}
console.log(soma);

But be careful if some asynchronous operation is occurring in your cycle:

var soma = 0;
for(var i = 0; i < 5; i++){
  $.get("https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty", function( data ) {
    soma += i
  });
}
console.log(soma);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The browser will not wait for the return of this operation

    
01.03.2017 / 10:59