]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/no-lone-blocks.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / no-lone-blocks.md
1 ---
2 title: no-lone-blocks
3 layout: doc
4 rule_type: suggestion
5 ---
6
7
8 In JavaScript, prior to ES6, standalone code blocks delimited by curly braces do not create a new scope and have no use. For example, these curly braces do nothing to `foo`:
9
10 ```js
11 {
12 var foo = bar();
13 }
14 ```
15
16 In ES6, code blocks may create a new scope if a block-level binding (`let` and `const`), a class declaration or a function declaration (in strict mode) are present. A block is not considered redundant in these cases.
17
18 ## Rule Details
19
20 This rule aims to eliminate unnecessary and potentially confusing blocks at the top level of a script or within other blocks.
21
22 Examples of **incorrect** code for this rule:
23
24 ::: incorrect
25
26 ```js
27 /*eslint no-lone-blocks: "error"*/
28
29 {}
30
31 if (foo) {
32 bar();
33 {
34 baz();
35 }
36 }
37
38 function bar() {
39 {
40 baz();
41 }
42 }
43
44 {
45 function foo() {}
46 }
47
48 {
49 aLabel: {
50 }
51 }
52
53 class C {
54 static {
55 {
56 foo();
57 }
58 }
59 }
60 ```
61
62 :::
63
64 Examples of **correct** code for this rule with ES6 environment:
65
66 ::: correct
67
68 ```js
69 /*eslint no-lone-blocks: "error"*/
70 /*eslint-env es6*/
71
72 while (foo) {
73 bar();
74 }
75
76 if (foo) {
77 if (bar) {
78 baz();
79 }
80 }
81
82 function bar() {
83 baz();
84 }
85
86 {
87 let x = 1;
88 }
89
90 {
91 const y = 1;
92 }
93
94 {
95 class Foo {}
96 }
97
98 aLabel: {
99 }
100
101 class C {
102 static {
103 lbl: {
104 if (something) {
105 break lbl;
106 }
107
108 foo();
109 }
110 }
111 }
112 ```
113
114 :::
115
116 Examples of **correct** code for this rule with ES6 environment and strict mode via `"parserOptions": { "sourceType": "module" }` in the ESLint configuration or `"use strict"` directive in the code:
117
118 ::: correct
119
120 ```js
121 /*eslint no-lone-blocks: "error"*/
122 /*eslint-env es6*/
123
124 "use strict";
125
126 {
127 function foo() {}
128 }
129 ```
130
131 :::