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:
false
0
undefined
NaN
null
""
In this case the value of i
will be decremented each time through the loop and when it hits the value of 0
, 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 of i
from someArray.length - 1
to 0
(inclusive) which are all the indexes of that array.
Your code example:
var i = someArray.length;
while (i--) {
console.log(someArray[i]);
}
creates the same output as this:
for (var i = someArray.length - 1; i >= 0; i--) {
console.log(someArray[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With