You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/rules/array-foreach.md
+27-32
Original file line number
Diff line number
Diff line change
@@ -1,38 +1,20 @@
1
-
# Array.forEach
1
+
# Array Foreach
2
2
3
3
Prefer `for...of` statement instead of `Array.forEach`.
4
4
5
-
```js
6
-
// bad
7
-
els.forEach(el=> {
8
-
el
9
-
})
10
-
11
-
// good
12
-
for (constelof els) {
13
-
el
14
-
}
15
-
```
16
-
17
-
## Why disallow `forEach`
5
+
## Rule Details
18
6
19
7
Here's a summary of why `forEach` is disallowed, and why we prefer `for...of` for almost any use-case of `forEach`:
20
8
21
-
- Allowing `forEach` encourages **layering of "bad practices"**, such as using `Array.from()` (which is less performant than using `for...of`).
22
-
- When more requirements are added on, `forEach` typically gets **chained** with other methods like `filter` or `map`, causing multiple iterations over the same Array. Encouraging `for` loops discourages chaining and encourages single-iteration logic (e.g. using a `continue` instead of `filter`).
23
-
-`for` loops are considered "more readable" and have **clearer intent**.
24
-
-`for...of` loops offer the **most flexibility** for iteration (especially vs `Array.from`).
25
-
26
-
For more detail, here is a breakdown of each of those points:
27
-
28
-
### Layering of bad practices
9
+
- Allowing `forEach` encourages **layering of "bad practices"**, such as using `Array.from()` (which is less performant than using `for...of`).
10
+
- When more requirements are added on, `forEach` typically gets **chained** with other methods like `filter` or `map`, causing multiple iterations over the same Array. Encouraging `for` loops discourages chaining and encourages single-iteration logic (e.g. using a `continue` instead of `filter`).
11
+
-`for` loops are considered "more readable" and have **clearer intent**.
12
+
-`for...of` loops offer the **most flexibility** for iteration (especially vs `Array.from`).
29
13
30
14
Typically developers will reach for a `forEach` when they want to iterate over a set of items. However not all "iterables" have access to Array methods. So a developer might convert their iterable to an Array by using `Array.from(iter).forEach()`. This code has introduced performance problems, where a `for...of` loop would be more performant.
31
15
32
16
`forEach` does not do anything special with the Array - it does not create a new array or does not aid in encapsulation (except for introducing a new lexical scope within the callback, which isn't a benefit considering we use `let`/`const`). We don't dissallow `map`/`filter`/`reduce` because they have a tangible effect - they create a new array - which would take _more_ code and be _less_ readable to do with a `for...of` loop, the exception being as more requirements are added, and we start chaining array methods together...
33
17
34
-
### Chaining
35
-
36
18
Often when using a method like `forEach` - when coming back to add new code, let's say to filter certain elements from the Array before operating on them, a developer is implicitly encouraged to use Array's method chaining to achieve this result. For example if we wanted to filter out bad apples from an Array of Apples, if the code already uses `forEach`, then its a simple addition to add `filter()`:
37
19
38
20
```diff
@@ -52,22 +34,18 @@ The problem we now have is that we're iterating multiple times over the items in
52
34
53
35
Chaning isn't always necessarily bad. Chaining can advertise a series of transformations that are independant from one another, and therefore aid readability. Additionally, sometimes the "goto-style" behaviour of `continue` in for loops can hamper readability. For small Arrays, performance is not going to be of concern, but caution should be applied where there is a potentially unbounded Array (such as iterating over a fetched users list) as performance can easily become a bottleneck when unchecked.
54
36
55
-
### Hiding Intent
56
-
57
-
The `forEach` method passes more than just the current item it is iterating over. The signature of the `forEach` callback method is `(cur: T, i: Number, all: []T) => void` and it can _additionally_ override the `receiver` (`this` value), meaning that often the _intent_ of what the callback does is hidden. To put this another way, there is _no way_ to know what the following code operates on without reading the implementation: `forEach(polishApple)`.
37
+
The `forEach` method passes more than just the current item it is iterating over. The signature of the `forEach` callback method is `(cur: T, i: Number, all: []T) => void` and it can _additionally_ override the `receiver` (`this` value), meaning that often the _intent_ of what the callback does is hidden. To put this another way, there is _no way_ to know what the following code operates on without reading the implementation: `forEach(polishApple)`.
58
38
59
39
The `for` loop avoids this issue. Calls are explicit within the `for` loop, as they are not passed around. For example:
60
40
61
41
```js
62
-
for(constappleof apples) {
42
+
for(constappleof apples) {
63
43
polishApple(apple)
64
44
}
65
45
```
66
46
67
47
We know this code can only possibly mutate `apple`, as the return value is discarded, there is no `receiver` (`this` value) as `.call()` is not used, and it cannot operate on the whole array of `apples` because it is not passed as an argument. In this respect, we can establish what the intent of `polishApple(apple)` is far more than `forEach(polishApple)`. It is too easy for `forEach` to obscure the intent.
68
48
69
-
### Flexibility
70
-
71
49
While `forEach` provides a set of arguments to the callback, it is still overall _less flexible_ than a `for` loop. A `for` loop can conditionally call the callback, can pass additional arguments to the callback (which would otherwise need to be hoisted or curried), can opt to change the `receiver` (`this` value) or not pass any `receiver` at all. This extra flexibility is the reason we almost always prefer to use `for` loops over any of the Array iteration methods.
72
50
73
51
A good example of how `for` loops provide flexibility, where `forEach` constrains it, is to see how an iteration would be refactored to handle async work. Consider the following...
@@ -98,7 +76,24 @@ Compare this to the `for` loop, which has a much simpler path to refactoring:
98
76
}
99
77
```
100
78
79
+
See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
Accessing `event.currentTarget` inside an `async function()` will likely be `null` as `currentTarget` is mutated as the event is propagated.
4
6
7
+
1. A `click` event is dispatched
8
+
2. The handler is invoked once with the expected `currentTarget`
9
+
3. An `await` defers the execution
10
+
4. The event dispatch continues, `event.currentTarget` is modified to point to the current target of another event handler and nulled out at the end of the dispatch
11
+
5. The async function resumes
12
+
6.`event.currentTarget` is now `null`
13
+
14
+
If you're using `async`, you'll need to synchronously create a reference to `currentTarget` before any async activity.
2. The handler is invoked once with the expected `currentTarget`
20
-
3. An `await` defers the execution
21
-
4. The event dispatch continues, `event.currentTarget` is modified to point to the current target of another event handler and nulled out at the end of the dispatch
22
-
5. The async function resumes
23
-
6.`event.currentTarget` is now `null`
24
-
25
-
## Solutions
26
-
27
-
If you're using `async`, you'll need to synchronously create a reference to `currentTarget` before any async activity.
2. This handler is scheduled but not ran immediately because its marked async.
17
9
3. The event dispatch completes and nothing has called `preventDefault()`_yet_ and the default click behavior occurs.
18
10
4. The async function is scheduled and runs.
19
11
5. Calling `preventDefault()` is now a no-op as the synchronous event dispatch has already completed.
20
12
21
-
## Solutions
22
-
23
13
If you're using `async`, you likely need to wait on a promise in the event handler. In this case you can split the event handler in two parts, one synchronous and asynchronous.
The Rails `form_tag` helper creates a `<form>` element with a `<input name="authenticity_token">` child element. The authenticity-token input tag contains a [Cross-Site Request Forgery (CSRF)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29) token that is verified by the Rails app when the form is submitted.
4
6
5
7
An attacker who is able to steal a user's CSRF token can perform a CSRF attack against that user. To reduce this risk, GitHub uses per-form CSRF tokens. This means that a form's method and action are embedded in that form's CSRF token. When the form is submitted, the Rails application verifies that the request's path and method match those of the CSRF token: A stolen token for the `POST /preview` endpoint will not be accepted for the `DELETE /github/github` endpoint.
6
8
7
-
## CSRF tokens in JavaScript
8
-
9
9
Requests initiated by JavaScript using XHR or Fetch still need to include a CSRF token. Prior to our use of per-form tokens, a common pattern for getting a valid CSRF token to include in a request was
10
10
11
+
Unless the JavaScript's request is for the same method/action as the form from which it takes the CSRF token, this CSRF token will _not_ be accepted by the Rails application.
12
+
13
+
The preferred way to make an HTTP request with JavaScript is to use the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API to serialize the input elements of a form:
Unless the JavaScript's request is for the same method/action as the form from which it takes the CSRF token, this CSRF token will _not_ be accepted by the Rails application.
16
-
17
-
The preferred way to make an HTTP request with JavaScript is to use the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) API to serialize the input elements of a form:
21
+
👍 Examples of **correct** code for this rule:
18
22
19
23
```erb
20
24
<%= form_tag "/my/endpoint" do %>
@@ -24,13 +28,13 @@ The preferred way to make an HTTP request with JavaScript is to use the [`FormDa
24
28
```
25
29
26
30
```js
27
-
on('click', '.js-my-button', function(e) {
31
+
on('click', '.js-my-button', function(e) {
28
32
constform=this.closest('form')
29
33
30
34
fetch(form.action, {
31
35
method:form.method,
32
36
body:newFormData(form)
33
-
}).then(function() {
37
+
}).then(function() {
34
38
alert('Success!')
35
39
})
36
40
@@ -45,14 +49,18 @@ An alternate, but less preferred approach is to include the a signed CSRF url in
0 commit comments