darkace darkace - 1 month ago 8
Javascript Question

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

Answer

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.

Comments