supporting foreach style for-loops
See original GitHub issueOne pattern I use a lot is a for-loop that looks like this:
for (let i = 0, token; token = tokens[i]; i++) {
// do something with token
}
This errors out, saying:
Expected a conditional expression and instead saw an assignment
I think this is totally appropriate. Unfortunately there’s no way to get around this error without changing the loop completely. Here’s a syntax that I think should work:
for (let i = 0, token; (token = tokens[i]); i++) {
// do something with token
}
Since it’s explicit that there’s an assignment, but it’ll give the same error as previously.
Issue Analytics
- State:
- Created 7 years ago
- Comments:15 (8 by maintainers)
Top Results From Across the Web
How does the Java 'for each' loop work? - Stack Overflow
The for-each loop, added in Java 5 (also called the "enhanced for loop"), ... basic for loop is simply the standard and expected...
Read more >The For-Each Loop
Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and...
Read more >Foreach loop - Wikipedia
In computer programming, foreach loop (or for each loop) is a control flow statement for traversing items in a collection. foreach is usually...
Read more >Iteration statements -for, foreach, do, and while - Microsoft Learn
The iteration statements repeatedly execute a statement or a block of statements. The for statement: executes its body while a specified Boolean ...
Read more >The foreach loop in C++ - DigitalOcean
So basically a for-each loop iterates over the elements of arrays, vectors, or any other data sets. It assigns the value of the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@dcousens whoops somehow I read this as your comment, my bad.
@jieverson
This approach saves a function allocation and allows you to do this more easily:
@dcousens yep:
also, it’s perfectly safe for other types when you have control over what you’re looping over, which happens quite a bit internally.