block-scoped-var
This rule generates warnings whenvar is used outside of the block in which it was defined, emulating C-style block scope.
Rule Type: Suggestion
Fixable: No
Fixable: No
Why This Rule Exists
JavaScript’svar is function-scoped, not block-scoped. This can cause confusion for developers coming from other languages or when expecting block-level scoping.
var.
Rule Details
This rule aims to reduce usage of variables outside their binding context, helping developers avoid bugs from variable hoisting.Examples
Incorrect Code
Correct Code
Understanding var Hoisting
Modern Alternative: Use let/const
Common Patterns
Loop Variables
Conditional Declarations
Migration Strategy
If you have a legacy codebase:- Enable this rule to find problematic
varusage - Fix issues by moving declarations to function level
- Gradually migrate to
let/const - Use no-var rule once migration is complete
When Not to Use It
Disable this rule if:- You’re already using
let/const(useno-varinstead) - Your team understands and accepts
varhoisting - You’re maintaining legacy code that can’t be changed
let/const with the no-var rule is better.
Related Rules
- no-var - Prefer let/const over var
- no-use-before-define - Disallow use before declaration
- prefer-const - Prefer const when variable isn’t reassigned