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

Asked

Viewed 31 times

2

For example:

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

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

My question is: Since the condition of if depends on the variable b, that comes from the loop for, the conditional if will only be executed when the loop for is completed, or I have to put the if in some kind of callback?

In short: I want to know if the browser "skips" the for before it ends, or whether I can trust the function/instruction below the for will only be executed when it is completed.

1 answer

4


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

first 5 loops:

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

where at the end of these our sum will be 10, hence for 100 loops 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’s an example with 200000000 (may take a while to finish running):

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

But beware, if in your cycle there’s some asynchronous operation going on:

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(s)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.