Skip to main content

block-scoped-var

This rule generates warnings when var is used outside of the block in which it was defined, emulating C-style block scope.
Rule Type: Suggestion
Fixable: No

Why This Rule Exists

JavaScript’s var is function-scoped, not block-scoped. This can cause confusion for developers coming from other languages or when expecting block-level scoping.
This rule helps catch bugs from variable hoisting by enforcing block-scope-like behavior for 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

var declarations are hoisted to the top of their function scope, but assignments remain in place.

Modern Alternative: Use let/const

The best solution is to use let or const instead of var. They are truly block-scoped.

Common Patterns

Loop Variables

Conditional Declarations

Migration Strategy

If you have a legacy codebase:
  1. Enable this rule to find problematic var usage
  2. Fix issues by moving declarations to function level
  3. Gradually migrate to let/const
  4. Use no-var rule once migration is complete

When Not to Use It

Disable this rule if:
  1. You’re already using let/const (use no-var instead)
  2. Your team understands and accepts var hoisting
  3. You’re maintaining legacy code that can’t be changed
For new code, using let/const with the no-var rule is better.

Further Reading