darkace
darkace

Reputation: 878

For loop and execution order

I have a for loop followed by a line of code (a done statement from mocha).

Will there be a situation where done() would be executed before the loop is complete? How does execution order work in javascript for a scenario like this?

for (let i=0; result.length < i; i++) {
  assert.equal(result[i].priority, 6);
}
done();

Upvotes: 1

Views: 146

Answers (4)

Dimse
Dimse

Reputation: 1506

Done will never be called before the loop is "done". But the definition of "done" looks strange in your loop.

The for loop should be

for(let i=0; i < result.length; i++){
    assert.equal(result[i].priority, 6);
}

When you only use result.length, it will skip the loop completely if result contains anything, since a positive number is a truthy value.

Upvotes: 1

Razvan Alex
Razvan Alex

Reputation: 1802

If you're looking to execute a function before the loop ends you can doo something like this

for (let i=0; result.length; i++) {
  assert.equal(result[i].priority, 6);
    if(condition) {
           break; // stops the loop
           done(); // execute function here
        }
    continue; // continue the loop until it ends
}

Upvotes: 0

Saurabh Sharma
Saurabh Sharma

Reputation: 2462

Just a small fiddle as a POC https://jsfiddle.net/66ppporc/ done() would always be called after the loop is complete.

And a quick read for you http://www.w3schools.com/tags/att_script_defer.asp

Upvotes: 0

Anna Jeanine
Anna Jeanine

Reputation: 4125

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the code. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the code.

Upvotes: 1

Related Questions