It works, but just looks like an anti pattern, especially since documentation describes how to define a for loop a particular way. I may avoid it, since it could affect other people’s understanding of your code - especially in an interview setting.
The former is more common. You can also see it in a couple of other languages. If you wanted to use the latter maybe you can use this instead (though I could be wrong) (assuming you only need the characters themselves and you don’t need the indexes in the loop)
for (let char of str) {
// do something with the `char`s
}
I think it’s a case of being “too clever”. It may work, but doesn’t communicate particularly well. Shorter isn’t necessarily better - more understandable/readable is always better. Consider the person who will inherit your code - in most organizations, you will be maintaining code you didn’t write yourself. So you’re going to want the programmer who wrote it to make it as clear as possible.
Also, generally speaking, you want to cache the length value in a loop … otherwise you are looking it up on every iteration of the loop, rather than doing it once prior to starting the loop.
I almost never use loops at all anymore.
In the case of operating over all of the characters in a string, I’d rather do str.split( ‘’ ) and use an Array method to iterate. Or, if I have to, use a while loop.
And the docs for for ... in, an approach I actually haven’t tried yet:
It’s worth noting this is ES2015 syntax. If you’re using CodePen, you need to ensure you have Babel selected as a processor for JavaScript I think. If your browser supports ES2015, you should be fine. YMMV.
I see, since the value of ary[3] is 0, it stops the loop.
I would have to write it as ary[i] >= 0 and even that only fixes the 0 problem,
the loop would still end if the value was a negative.