]>
Commit | Line | Data |
---|---|---|
8f9d1d4d DC |
1 | --- |
2 | title: guard-for-in | |
3 | layout: doc | |
4 | rule_type: suggestion | |
5 | related_rules: | |
6 | - no-prototype-builtins | |
7 | further_reading: | |
8 | - https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/ | |
9 | - https://2ality.com/2012/01/objects-as-maps.html | |
10 | --- | |
11 | ||
eb39fafa DC |
12 | |
13 | Looping over objects with a `for in` loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop. | |
14 | ||
15 | ```js | |
16 | for (key in foo) { | |
17 | doSomething(key); | |
18 | } | |
19 | ``` | |
20 | ||
8f9d1d4d | 21 | Note that simply checking `foo.hasOwnProperty(key)` is likely to cause an error in some cases; see [no-prototype-builtins](no-prototype-builtins). |
eb39fafa DC |
22 | |
23 | ## Rule Details | |
24 | ||
25 | This rule is aimed at preventing unexpected behavior that could arise from using a `for in` loop without filtering the results in the loop. As such, it will warn when `for in` loops do not filter their results with an `if` statement. | |
26 | ||
27 | Examples of **incorrect** code for this rule: | |
28 | ||
8f9d1d4d DC |
29 | ::: incorrect |
30 | ||
eb39fafa DC |
31 | ```js |
32 | /*eslint guard-for-in: "error"*/ | |
33 | ||
34 | for (key in foo) { | |
35 | doSomething(key); | |
36 | } | |
37 | ``` | |
38 | ||
8f9d1d4d DC |
39 | ::: |
40 | ||
eb39fafa DC |
41 | Examples of **correct** code for this rule: |
42 | ||
8f9d1d4d DC |
43 | ::: correct |
44 | ||
eb39fafa DC |
45 | ```js |
46 | /*eslint guard-for-in: "error"*/ | |
47 | ||
48 | for (key in foo) { | |
49 | if (Object.prototype.hasOwnProperty.call(foo, key)) { | |
50 | doSomething(key); | |
51 | } | |
52 | } | |
53 | ||
54 | for (key in foo) { | |
55 | if ({}.hasOwnProperty.call(foo, key)) { | |
56 | doSomething(key); | |
57 | } | |
58 | } | |
59 | ``` | |
60 | ||
8f9d1d4d | 61 | ::: |