Skip to content

Commit 72d41f0

Browse files
not-an-aardvarkbtmills
authored andcommitted
Fix: no-var autofix syntax error in single-line statements (fixes #7961) (#7962)
1 parent b9e5b68 commit 72d41f0

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

lib/rules/no-var.js

+12
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ module.exports = {
209209
* - A variable is used from a closure within a loop.
210210
* - A variable might be used before it is assigned within a loop.
211211
* - A variable might be used in TDZ.
212+
* - A variable is declared in statement position (e.g. a single-line `IfStatement`)
212213
*
213214
* ## A variable is declared on a SwitchCase node.
214215
*
@@ -270,6 +271,17 @@ module.exports = {
270271
}
271272
}
272273

274+
if (
275+
!isLoopAssignee(node) &&
276+
node.parent.type !== "BlockStatement" &&
277+
node.parent.type !== "Program" &&
278+
node.parent.type !== "SwitchCase"
279+
) {
280+
281+
// If the declaration is not in a block, e.g. `if (foo) var bar = 1;`, then it can't be fixed.
282+
return false;
283+
}
284+
273285
return true;
274286
}
275287

tests/lib/rules/no-var.js

+9
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,15 @@ ruleTester.run("no-var", rule, {
215215
errors: [
216216
"Unexpected var, use let or const instead."
217217
]
218+
},
219+
220+
// https://github.com/eslint/eslint/issues/7961
221+
{
222+
code: "if (foo) var bar = 1;",
223+
output: "if (foo) var bar = 1;",
224+
errors: [
225+
{ message: "Unexpected var, use let or const instead.", type: "VariableDeclaration" }
226+
]
218227
}
219228
]
220229
});

0 commit comments

Comments
 (0)