consistent-function-scoping
ESLint rule documentation for consistent-function-scoping
๐ก Live from GitHub โ This documentation is fetched directly from consistent-function-scoping.md and cached for 6 hours.
Keywords: function scope, hoisting, nested functions, ESLint rule, performance, LLM-optimized
Move functions to the highest possible scope
Move functions to the highest possible scope. This rule is part of eslint-plugin-maintainability.
Quick Summary
| Aspect | Details |
|---|---|
| Severity | Warning (code quality) |
| Auto-Fix | โ No (requires manual move) |
| Category | Quality |
| ESLint MCP | โ Optimized for ESLint MCP integration |
| Best For | Performance optimization, code organization |
Rule Details
Functions that don't use variables from their parent scope should be moved to a higher scope.
Why This Matters
| Issue | Impact | Solution |
|---|---|---|
| โก Performance | Recreated on each call | Move to outer scope |
| ๐ Readability | Deep nesting | Flatten structure |
| ๐งช Testability | Hard to test nested functions | Extract for testing |
Examples
โ Incorrect
function outer() {
// This function doesn't use any variables from outer
function helper(x: number) {
return x * 2;
}
return [1, 2, 3].map(helper);
}โ Correct
// Moved to module scope
function helper(x: number) {
return x * 2;
}
function outer() {
return [1, 2, 3].map(helper);
}
// Or when closure is needed (correct nesting)
function createMultiplier(factor: number) {
return function multiply(x: number) { // Uses factor from parent
return x * factor;
};
}Configuration Examples
Basic Usage
{
rules: {
'architecture/consistent-function-scoping': 'warn'
}
}Related Rules
cognitive-complexity- Code complexity
Further Reading
- Closures - MDN - JavaScript closures
Known False Negatives
The following patterns are not detected due to static analysis limitations:
Dynamic Variable References
Why: Static analysis cannot trace values stored in variables or passed through function parameters.
// โ NOT DETECTED - Value from variable
const value = externalSource();
processValue(value); // Variable origin not trackedMitigation: Implement runtime validation and review code manually. Consider using TypeScript branded types for validated inputs.
Imported Values
Why: When values come from imports, the rule cannot analyze their origin or construction.
// โ NOT DETECTED - Value from import
import { getValue } from './helpers';
processValue(getValue()); // Cross-file not trackedMitigation: Ensure imported values follow the same constraints. Use TypeScript for type safety.