]>
Commit | Line | Data |
---|---|---|
8f9d1d4d DC |
1 | --- |
2 | title: guard-for-in | |
8f9d1d4d DC |
3 | rule_type: suggestion |
4 | related_rules: | |
f2a92ac6 | 5 | - prefer-object-has-own |
8f9d1d4d DC |
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 | ||
f2a92ac6 DC |
21 | For codebases that do not support ES2022, `Object.prototype.hasOwnProperty.call(foo, key)` can be used as a check that the property is not inherited. |
22 | ||
23 | For codebases that do support ES2022, `Object.hasOwn(foo, key)` can be used as a shorter alternative; see [prefer-object-has-own](prefer-object-has-own). | |
24 | ||
8f9d1d4d | 25 | 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 |
26 | |
27 | ## Rule Details | |
28 | ||
29 | 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. | |
30 | ||
31 | Examples of **incorrect** code for this rule: | |
32 | ||
8f9d1d4d DC |
33 | ::: incorrect |
34 | ||
eb39fafa DC |
35 | ```js |
36 | /*eslint guard-for-in: "error"*/ | |
37 | ||
38 | for (key in foo) { | |
39 | doSomething(key); | |
40 | } | |
41 | ``` | |
42 | ||
8f9d1d4d DC |
43 | ::: |
44 | ||
eb39fafa DC |
45 | Examples of **correct** code for this rule: |
46 | ||
8f9d1d4d DC |
47 | ::: correct |
48 | ||
eb39fafa DC |
49 | ```js |
50 | /*eslint guard-for-in: "error"*/ | |
51 | ||
f2a92ac6 DC |
52 | for (key in foo) { |
53 | if (Object.hasOwn(foo, key)) { | |
54 | doSomething(key); | |
55 | } | |
56 | } | |
57 | ||
eb39fafa DC |
58 | for (key in foo) { |
59 | if (Object.prototype.hasOwnProperty.call(foo, key)) { | |
60 | doSomething(key); | |
61 | } | |
62 | } | |
63 | ||
64 | for (key in foo) { | |
65 | if ({}.hasOwnProperty.call(foo, key)) { | |
66 | doSomething(key); | |
67 | } | |
68 | } | |
69 | ``` | |
70 | ||
8f9d1d4d | 71 | ::: |