]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-redeclare.md
import 8.3.0 source
[pve-eslint.git] / eslint / docs / rules / no-redeclare.md
1 # disallow variable redeclaration (no-redeclare)
2
3 In JavaScript, it's possible to redeclare the same variable name using `var`. This can lead to confusion as to where the variable is actually declared and initialized.
4
5 ## Rule Details
6
7 This rule is aimed at eliminating variables that have multiple declarations in the same scope.
8
9 Examples of **incorrect** code for this rule:
10
11 ```js
12 /*eslint no-redeclare: "error"*/
13
14 var a = 3;
15 var a = 10;
16
17 class C {
18 foo() {
19 var b = 3;
20 var b = 10;
21 }
22
23 static {
24 var c = 3;
25 var c = 10;
26 }
27 }
28 ```
29
30 Examples of **correct** code for this rule:
31
32 ```js
33 /*eslint no-redeclare: "error"*/
34
35 var a = 3;
36 a = 10;
37
38 class C {
39 foo() {
40 var b = 3;
41 b = 10;
42 }
43
44 static {
45 var c = 3;
46 c = 10;
47 }
48 }
49
50 ```
51
52 ## Options
53
54 This rule takes one optional argument, an object with a boolean property `"builtinGlobals"`. It defaults to `true`.
55 If set to `true`, this rule also checks redeclaration of built-in globals, such as `Object`, `Array`, `Number`...
56
57 ### builtinGlobals
58
59 The `"builtinGlobals"` option will check for redeclaration of built-in globals in global scope.
60
61 Examples of **incorrect** code for the `{ "builtinGlobals": true }` option:
62
63 ```js
64 /*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
65
66 var Object = 0;
67 ```
68
69 Examples of **incorrect** code for the `{ "builtinGlobals": true }` option and the `browser` environment:
70
71 ```js
72 /*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/
73 /*eslint-env browser*/
74
75 var top = 0;
76 ```
77
78 The `browser` environment has many built-in global variables (for example, `top`). Some of built-in global variables cannot be redeclared.
79
80 Note that when using the `node` or `commonjs` environments (or `ecmaFeatures.globalReturn`, if using the default parser), the top scope of a program is not actually the global scope, but rather a "module" scope. When this is the case, declaring a variable named after a builtin global is not a redeclaration, but rather a shadowing of the global variable. In that case, the [`no-shadow`](no-shadow.md) rule with the `"builtinGlobals"` option should be used.
81
82 ## Related Rules
83
84 * [no-shadow](no-shadow.md)