]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/dot-notation.md
import 8.3.0 source
[pve-eslint.git] / eslint / docs / rules / dot-notation.md
1 # Require Dot Notation (dot-notation)
2
3 In JavaScript, one can access properties using the dot notation (`foo.bar`) or square-bracket notation (`foo["bar"]`). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
4
5 ```js
6 foo["bar"];
7 ```
8
9 ## Rule Details
10
11 This rule is aimed at maintaining code consistency and improving code readability by encouraging use of the dot notation style whenever possible. As such, it will warn when it encounters an unnecessary use of square-bracket notation.
12
13 Examples of **incorrect** code for this rule:
14
15 ```js
16 /*eslint dot-notation: "error"*/
17
18 var x = foo["bar"];
19 ```
20
21 Examples of **correct** code for this rule:
22
23 ```js
24 /*eslint dot-notation: "error"*/
25
26 var x = foo.bar;
27
28 var x = foo[bar]; // Property name is a variable, square-bracket notation required
29 ```
30
31 ## Options
32
33 This rule accepts a single options argument:
34
35 * Set the `allowKeywords` option to `false` (default is `true`) to follow ECMAScript version 3 compatible style, avoiding dot notation for reserved word properties.
36 * Set the `allowPattern` option to a regular expression string to allow bracket notation for property names that match a pattern (by default, no pattern is tested).
37
38 ### allowKeywords
39
40 Examples of **correct** code for the `{ "allowKeywords": false }` option:
41
42 ```js
43 /*eslint dot-notation: ["error", { "allowKeywords": false }]*/
44
45 var foo = { "class": "CS 101" }
46 var x = foo["class"]; // Property name is a reserved word, square-bracket notation required
47 ```
48
49 Examples of additional **correct** code for the `{ "allowKeywords": false }` option:
50
51 ```js
52 /*eslint dot-notation: ["error", { "allowKeywords": false }]*/
53
54 class C {
55 #in;
56 foo() {
57 this.#in; // Dot notation is required for private identifiers
58 }
59 }
60 ```
61
62 ### allowPattern
63
64 For example, when preparing data to be sent to an external API, it is often required to use property names that include underscores. If the `camelcase` rule is in effect, these [snake case](https://en.wikipedia.org/wiki/Snake_case) properties would not be allowed. By providing an `allowPattern` to the `dot-notation` rule, these snake case properties can be accessed with bracket notation.
65
66 Examples of **correct** code for the sample `{ "allowPattern": "^[a-z]+(_[a-z]+)+$" }` option:
67
68 ```js
69 /*eslint camelcase: "error"*/
70 /*eslint dot-notation: ["error", { "allowPattern": "^[a-z]+(_[a-z]+)+$" }]*/
71
72 var data = {};
73 data.foo_bar = 42;
74
75 var data = {};
76 data["fooBar"] = 42;
77
78 var data = {};
79 data["foo_bar"] = 42; // no warning
80 ```