]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-global-assign.md
b3718d178b26035e01aa5cc7072d842ab662aed3
[pve-eslint.git] / eslint / docs / rules / no-global-assign.md
1 # Disallow assignment to native objects or read-only global variables (no-global-assign)
2
3 JavaScript environments contain a number of built-in global variables, such as `window` in browsers and `process` in Node.js. In almost all cases, you don't want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don't want to do this in browser code:
4
5 ```js
6 window = {};
7 ```
8
9 While examples such as `window` are obvious, there are often hundreds of built-in global objects provided by JavaScript environments. It can be hard to know if you're assigning to a global variable or not.
10
11 ## Rule Details
12
13 This rule disallows modifications to read-only global variables.
14
15 ESLint has the capability to configure global variables as read-only.
16
17 * [Specifying Environments](../user-guide/configuring#specifying-environments)
18 * [Specifying Globals](../user-guide/configuring#specifying-globals)
19
20 Examples of **incorrect** code for this rule:
21
22 ```js
23 /*eslint no-global-assign: "error"*/
24
25 Object = null
26 undefined = 1
27 ```
28
29 ```js
30 /*eslint no-global-assign: "error"*/
31 /*eslint-env browser*/
32
33 window = {}
34 length = 1
35 top = 1
36 ```
37
38 ```js
39 /*eslint no-global-assign: "error"*/
40 /*global a:readonly*/
41
42 a = 1
43 ```
44
45 Examples of **correct** code for this rule:
46
47 ```js
48 /*eslint no-global-assign: "error"*/
49
50 a = 1
51 var b = 1
52 b = 2
53 ```
54
55 ```js
56 /*eslint no-global-assign: "error"*/
57 /*eslint-env browser*/
58
59 onload = function() {}
60 ```
61
62 ```js
63 /*eslint no-global-assign: "error"*/
64 /*global a:writable*/
65
66 a = 1
67 ```
68
69 ## Options
70
71 This rule accepts an `exceptions` option, which can be used to specify a list of builtins for which reassignments will be allowed:
72
73 ```json
74 {
75 "rules": {
76 "no-global-assign": ["error", {"exceptions": ["Object"]}]
77 }
78 }
79 ```
80
81 ## When Not To Use It
82
83 If you are trying to override one of the native objects.
84
85 ## Related Rules
86
87 * [no-extend-native](no-extend-native.md)
88 * [no-redeclare](no-redeclare.md)
89 * [no-shadow](no-shadow.md)