diff --git a/README.md b/README.md index b758421d..381d5c6b 100644 --- a/README.md +++ b/README.md @@ -1245,6 +1245,47 @@ Other Style Guides ``` - [15.4](#15.4) 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) 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) Ternaries should not be nested and generally be single line expressions. diff --git a/packages/eslint-config-airbnb/rules/best-practices.js b/packages/eslint-config-airbnb/rules/best-practices.js index c2af1b78..d8b94e9b 100644 --- a/packages/eslint-config-airbnb/rules/best-practices.js +++ b/packages/eslint-config-airbnb/rules/best-practices.js @@ -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