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.
- Do you understand what the code is doing?
- Is anyone else expected to read the code and understand what it is doing, and will it be relatively easy for them to read and understand what the code is doing?
- Will the code be used as part of the development code on a project for a group or organization that implements Programming Style guidelines?
To be more specific, here are some pros and cons using the code in your example.
- In specific use cases, such as an array which is guaranteed to contain objects or other "truthy" values, this way is concise, doubling as a conditional statement and an assignment statement.
- If the array contains
"" 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
"", 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.