Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Banning for loops when a TS for(...of...) loop might be better #1335

Closed
ChrisMBarr opened this issue Jun 24, 2016 · 4 comments
Closed

Banning for loops when a TS for(...of...) loop might be better #1335

ChrisMBarr opened this issue Jun 24, 2016 · 4 comments

Comments

@ChrisMBarr
Copy link
Contributor

Basically a standard for loop should only be allowed if the incrementer variable is used in the block of the loop for anything other than accessing the current array item.

👍 This is Fine since the array index is needed for something

for (var j = 0; j <= arr.length; j++) {
    doMath(j);
}

👎 This could be replaced with a for(...of...) loop since the index is only used to access the array

for (var i = 0; i <= arr.length; i++) {
    doThing(arr[i]);
}

Here's the preferred way to write the above loop

for (var item of arr) {
    doThing(item);
}

Is this a feasible rule idea? I've already begun some work on it, but I'll work on it more later. Right now it's only partially working since I'm not sure how to look for variable usages within a certain scope/Block/SyntaxList. Any tips would be appreciated!

@adidahiya
Copy link
Contributor

I'm a fan of this rule; it could be called prefer-for-of-loop.

I'm not sure how to look for variable usages within a certain scope/Block/SyntaxList

One idea is to use the regular languageService.getDocumentHighlights method, iterate through the highlights and verify that the source code positions of those spans are within the Block you are searching within.

@scameron
Copy link

scameron commented Jun 1, 2018

If you are adding elements to the end of the array being iterated, don’t you need to use a standard for? In this case, a reference to the index variable might not appear inside the loop.

@beenotung
Copy link

beenotung commented Aug 17, 2019

I agree for-of is more readable and easier to maintain, however, it may hurt the performance.

For example, in Firefox: for loop with index has 219,705 ops/sec, while for-of has only 35,827 ops/sec. Which is 84% slower

The cost maybe fine for typical application.
But that should not be the case for general library, that can be potentially be in the critical path.

demo:
https://jsperf.com/foreach/19

@wortwart
Copy link

wortwart commented Sep 3, 2019

This rule should not be default because in the DOM there are array-like objects which you can't iterate with for..of or .forEach() - at least not without extra hassle. I've been struggling repeatedly with this rule in node collections like you get with document.querySelectorAll().
Classic for loops are highly performant, simple, and readable and should IMHO be considered good practice.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants