Skip to content

Commit

Permalink
Fix: prefer-const false positive at non-blocked if (fixes #5610)
Browse files Browse the repository at this point in the history
  • Loading branch information
mysticatea committed Mar 19, 2016
1 parent c0a7e0e commit 9a22625
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
12 changes: 12 additions & 0 deletions docs/rules/prefer-const.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ for (let i in [1,2,3]) {
for (let a of [1,2,3]) {
console.log(a);
}

// the initializer is separated.
let a;
a = 0;
console.log(a);
```

The following patterns are not considered problems:
Expand All @@ -52,6 +57,13 @@ for (let i = 0, end = 10; i < end; ++i) {
console.log(a);
}

// the initializer is located at another block.
let a;
if (true) {
a = 0;
}
console.log(a);

// suggest to use `no-var` rule.
var b = 3;
console.log(b);
Expand Down
4 changes: 3 additions & 1 deletion lib/rules/prefer-const.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//------------------------------------------------------------------------------

var PATTERN_TYPE = /^(?:.+?Pattern|RestElement|Property)$/;
var DECLARATION_HOST_TYPE = /^(?:Program|BlockStatement|SwitchCase)$/;

/**
* Adds multiple items to the tail of an array.
Expand Down Expand Up @@ -47,7 +48,8 @@ function canBecomeVariableDeclaration(identifier) {
node.type === "VariableDeclarator" ||
(
node.type === "AssignmentExpression" &&
node.parent.type === "ExpressionStatement"
node.parent.type === "ExpressionStatement" &&
DECLARATION_HOST_TYPE.test(node.parent.parent.type)
)
);
}
Expand Down
6 changes: 6 additions & 0 deletions tests/lib/rules/prefer-const.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ ruleTester.run("prefer-const", rule, {
parserOptions: { ecmaVersion: 6 }
},
{ code: "/*exported a*/ let a; function init() { a = foo(); }", parserOptions: { ecmaVersion: 6 } },
{ code: "let a; if (true) a = 0; foo(a);", parserOptions: { ecmaVersion: 6 } },

// The assignment is located in a different scope.
// Those are warned by prefer-smaller-scope.
Expand Down Expand Up @@ -147,6 +148,11 @@ ruleTester.run("prefer-const", rule, {
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "'x' is never reassigned, use 'const' instead.", type: "Identifier"}]
},
{
code: "switch (a) { case 0: let x; x = 0; }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "'x' is never reassigned, use 'const' instead.", type: "Identifier"}]
},
{
code: "(function() { let x; x = 1; })();",
parserOptions: { ecmaVersion: 6 },
Expand Down

0 comments on commit 9a22625

Please sign in to comment.