Just saw a code snippet that used an array pop assignment in the while condition; was wondering if this is acceptable/good practice?
var arr = [0,1,2,3,4,5]; var current; while (current = arr.pop()) { // do stuff to each element stored in current }
It is not necessarily wrong if the code does what it is supposed to do, however, decisions such as this can be a matter of taste or opinion in personally written code. Conversely, avoiding this particular arrangement of logic may be a requirement of an employer.
Here are the things to consider.
To be more specific, here are some pros and cons using the code in your example.
undefined
, null
, 0
, false
, NaN
, ""
or has "holes" in it, this way will fail."Holes" means when the array has a length greater than 0 and some (or all) of the elements of the array have not been assigned a value.
"Truthy" means values that do not evaluate to false ( see the cons ). Do not forget NaN
or ""
, I almost just did.
The code in your example already contains a bug. The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element in the array.
while(arr.length) doStuffWithElement(arr.pop())
CommentedFeb 1, 2021 at 2:55If the intention is to process the array like a queue or a stack, wherein items are removed as they're processed, yes. This is a pretty standard approach.
In fact, you'll sometimes see this sort of loop for tree traversals where stack overflows, or the need to pause and resume, are a potential problem in the recursive solution.
for
look or the newerfor/of
or.forEach()
to just iterate it.