UNPKG

1.39 kBMarkdownView Raw
1# `prefer-for-of`
2
3Prefer a ‘for-of’ loop over a standard ‘for’ loop if the index is only used to access the array being iterated.
4
5This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.
6
7## Rule Details
8
9For cases where the index is only used to read from the array being iterated, a for-of loop is easier to read and write.
10
11Examples of code for this rule:
12
13<!--tabs-->
14
15### ❌ Incorrect
16
17```js
18for (let i = 0; i < arr.length; i++) {
19 console.log(arr[i]);
20}
21```
22
23### ✅ Correct
24
25```js
26for (const x of arr) {
27 console.log(x);
28}
29
30for (let i = 0; i < arr.length; i++) {
31 // i is used to write to arr, so for-of could not be used.
32 arr[i] = 0;
33}
34
35for (let i = 0; i < arr.length; i++) {
36 // i is used independent of arr, so for-of could not be used.
37 console.log(i, arr[i]);
38}
39```
40
41## Options
42
43```jsonc
44// .eslintrc.json
45{
46 "rules": {
47 "@typescript-eslint/prefer-for-of": "warn"
48 }
49}
50```
51
52This rule is not configurable.
53
54## When Not To Use It
55
56If you transpile for browsers that do not support for-of loops, you may wish to use traditional for loops that produce more compact code.
57
58## Related To
59
60- TSLint: ['prefer-for-of'](https://palantir.github.io/tslint/rules/prefer-for-of/)
61
62## Attributes
63
64- Configs:
65 - [ ] ✅ Recommended
66 - [x] 🔒 Strict
67- [ ] 🔧 Fixable
68- [ ] 💭 Requires type information