Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a reverse while loop know when to stop in JavaScript?

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?

like image 607
Jacob Avatar asked Nov 30 '22 15:11

Jacob


1 Answers

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]);
}
like image 131
jfriend00 Avatar answered Dec 06 '22 15:12

jfriend00