In JavaScript, I have recently came across how reverse while loops are faster.
I have seen them in this form:
var i = someArray.length;
while (i--) {
console.log(someArray[i]);
}
I tested this out and it stopped once it went through the whole array.
How does it know when to stop once it completes the array?
A while loop evaluates the expression inside the parentheses each time through the loop. When that expression gets to a falsey value, the loop will stop.
Examples of falsey values are:
In this case the value of
iwill be decremented each time through the loop and when it hits the value of0, the loop will stop. Because it’s a post decrement operator, the value of the expression is checked before the decrement. This means that the inner loop will see values ofifromsomeArray.length - 1to0(inclusive) which are all the indexes of that array.Your code example:
creates the same output as this: