]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/guard-for-in.md
28dc1637ff4c1567362257295f815a34c9700bcc
[pve-eslint.git] / eslint / docs / rules / guard-for-in.md
1 # Require Guarding for-in (guard-for-in)
2
3 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.
4
5 ```js
6 for (key in foo) {
7 doSomething(key);
8 }
9 ```
10
11 Note that simply checking `foo.hasOwnProperty(key)` is likely to cause an error in some cases; see [no-prototype-builtins](no-prototype-builtins.md).
12
13 ## Rule Details
14
15 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.
16
17 Examples of **incorrect** code for this rule:
18
19 ```js
20 /*eslint guard-for-in: "error"*/
21
22 for (key in foo) {
23 doSomething(key);
24 }
25 ```
26
27 Examples of **correct** code for this rule:
28
29 ```js
30 /*eslint guard-for-in: "error"*/
31
32 for (key in foo) {
33 if (Object.prototype.hasOwnProperty.call(foo, key)) {
34 doSomething(key);
35 }
36 }
37
38 for (key in foo) {
39 if ({}.hasOwnProperty.call(foo, key)) {
40 doSomething(key);
41 }
42 }
43 ```
44
45 ## Related Rules
46
47 * [no-prototype-builtins](no-prototype-builtins.md)
48
49 ## Further Reading
50
51 * [Exploring JavaScript for-in loops](https://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/)
52 * [The pitfalls of using objects as maps in JavaScript](http://2ality.com/2012/01/objects-as-maps.html)