mirror of
https://github.com/airbnb/javascript.git
synced 2026-01-14 05:58:04 -05:00
Avoid lexical declarations in case/default clauses
This commit adds guidance warning people to avoid lexical declarations in case/default clauses and enables the corresponding ESLint rule. http://eslint.org/docs/rules/no-case-declarations.html We didn't have a section on switch statements yet, so I thought about starting one. It seemed like it would best fit between section 15 (Comparison Operators & Equality) and section 16 (Blocks), but I didn't want to mess up all of the following numberings, since people probably have references to them. I considered adding this near the end to minimize this effect, but it really seemed to belong near these other things. I landed on appending it to Section 15 (Comparison Operators & Equality) and I think it sorta fits there since switch statements are a related concept.
This commit is contained in:
41
README.md
41
README.md
@@ -1245,6 +1245,47 @@ Other Style Guides
|
||||
```
|
||||
|
||||
- [15.4](#15.4) <a name='15.4'></a> For more information see [Truth Equality and JavaScript](http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) by Angus Croll.
|
||||
- [15.5](#15.5) <a name='15.5'></a> Use braces to create blocks in `case` and `default` clauses that contain lexical declarations (e.g. `let`, `const`, `function`, and `class`).
|
||||
|
||||
> Why? Lexical declarations are visible in the entire `switch` block but only get initialized when assigned, which only happens when its `case` is reached. This causes problems when multiple `case` clauses attempt to define the same thing.
|
||||
|
||||
eslint rules: [`no-case-declarations`](http://eslint.org/docs/rules/no-case-declarations.html).
|
||||
|
||||
```javascript
|
||||
// bad
|
||||
switch (foo) {
|
||||
case 1:
|
||||
let x = 1;
|
||||
break;
|
||||
case 2:
|
||||
const y = 2;
|
||||
break;
|
||||
case 3:
|
||||
function f() {}
|
||||
break;
|
||||
default:
|
||||
class C {}
|
||||
}
|
||||
|
||||
// good
|
||||
switch (foo) {
|
||||
case 1: {
|
||||
let x = 1;
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
const y = 2;
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
function f() {}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
class C {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [15.5](#15.5) <a name='15.5'></a> Ternaries should not be nested and generally be single line expressions.
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ module.exports = {
|
||||
'no-alert': 1,
|
||||
// disallow use of arguments.caller or arguments.callee
|
||||
'no-caller': 2,
|
||||
// disallow lexical declarations in case/default clauses
|
||||
'no-case-declaration': 2,
|
||||
// disallow division operators explicitly at beginning of regular expression
|
||||
'no-div-regex': 0,
|
||||
// disallow else after a return in an if
|
||||
|
||||
Reference in New Issue
Block a user