Site logo

While Loop with Array.pop() Gotcha

By Harbs

A number of us have been using a while(obj=array.pop()){} construct for a while. (I believe Marc was the one to introduce this construct to this forum.)
While this is considerably more efficient than a standard for loop when you don't need the array when the loop is done, there's a not-so-obvious gotcha:
0 in javascript is evaluated to false, so: while(0) is equivalent to while(false).
If you have an loop like this:

ar = [1,0,8,6];
while(a=ar.pop()){ // do your stuff }

6 and 8 will resolve true, but 0 will not. The loop will exit when it hits 0, and neither 0 nor 1 will be processed.
This loop is no good either:

ar = [1,0,8,6];
while(a=ar.pop() != null){ //do your stuff }

because "a" will evaluate to either true or false instead of the value of the array because statements are processed backwards (i.e. a = (ar.pop != null)).
Instead you need (note the extra parenthesis):

ar = [1,0,8,6];
while((a=ar.pop()) != null){ //do your stuff }