]> git.proxmox.com Git - pve-eslint.git/blame - eslint/docs/src/rules/no-lone-blocks.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / no-lone-blocks.md
CommitLineData
8f9d1d4d
DC
1---
2title: no-lone-blocks
3layout: doc
4rule_type: suggestion
5---
6
eb39fafa
DC
7
8In 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
16In 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
20This rule aims to eliminate unnecessary and potentially confusing blocks at the top level of a script or within other blocks.
21
22Examples of **incorrect** code for this rule:
23
8f9d1d4d
DC
24::: incorrect
25
eb39fafa
DC
26```js
27/*eslint no-lone-blocks: "error"*/
28
29{}
30
31if (foo) {
32 bar();
33 {
34 baz();
35 }
36}
37
38function bar() {
39 {
40 baz();
41 }
42}
43
44{
45 function foo() {}
46}
47
48{
49 aLabel: {
50 }
51}
609c276f
TL
52
53class C {
54 static {
55 {
56 foo();
57 }
58 }
59}
eb39fafa
DC
60```
61
8f9d1d4d
DC
62:::
63
eb39fafa
DC
64Examples of **correct** code for this rule with ES6 environment:
65
8f9d1d4d
DC
66::: correct
67
eb39fafa
DC
68```js
69/*eslint no-lone-blocks: "error"*/
70/*eslint-env es6*/
71
72while (foo) {
73 bar();
74}
75
76if (foo) {
77 if (bar) {
78 baz();
79 }
80}
81
82function 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
98aLabel: {
99}
609c276f
TL
100
101class C {
102 static {
103 lbl: {
104 if (something) {
105 break lbl;
106 }
107
108 foo();
109 }
110 }
111}
eb39fafa
DC
112```
113
8f9d1d4d
DC
114:::
115
eb39fafa
DC
116Examples 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
8f9d1d4d
DC
118::: correct
119
eb39fafa
DC
120```js
121/*eslint no-lone-blocks: "error"*/
122/*eslint-env es6*/
123
124"use strict";
125
126{
127 function foo() {}
128}
129```
8f9d1d4d
DC
130
131:::