Skip to content

Commit

Permalink
Fix: no-var autofix syntax error in single-line statements (fixes #7961
Browse files Browse the repository at this point in the history
…) (#7962)
  • Loading branch information
not-an-aardvark authored and btmills committed Jan 23, 2017
1 parent b9e5b68 commit 72d41f0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/rules/no-var.js
Expand Up @@ -209,6 +209,7 @@ module.exports = {
* - A variable is used from a closure within a loop.
* - A variable might be used before it is assigned within a loop.
* - A variable might be used in TDZ.
* - A variable is declared in statement position (e.g. a single-line `IfStatement`)
*
* ## A variable is declared on a SwitchCase node.
*
Expand Down Expand Up @@ -270,6 +271,17 @@ module.exports = {
}
}

if (
!isLoopAssignee(node) &&
node.parent.type !== "BlockStatement" &&
node.parent.type !== "Program" &&
node.parent.type !== "SwitchCase"
) {

// If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed.
return false;
}

return true;
}

Expand Down
9 changes: 9 additions & 0 deletions tests/lib/rules/no-var.js
Expand Up @@ -215,6 +215,15 @@ ruleTester.run("no-var", rule, {
errors: [
"Unexpected var, use let or const instead."
]
},

// https://github.com/eslint/eslint/issues/7961
{
code: "if (foo) var bar = 1;",
output: "if (foo) var bar = 1;",
errors: [
{ message: "Unexpected var, use let or const instead.", type: "VariableDeclaration" }
]
}
]
});

0 comments on commit 72d41f0

Please sign in to comment.