unicorn/prefer-smaller-scope
eslint-plugin-unicorn
Safe autofix
eslint.config.js
import unicorn from "eslint-plugin-unicorn";
export default [
{
plugins: { unicorn },
rules: {
"unicorn/prefer-smaller-scope": "error",
},
},
];Prefer declaring variables and type aliases in the smallest possible scope.
function foo() {
let value;
while (condition) {
value = getValue();
console.log(value);
}
}function foo() {
let value;
if (condition) {
value = getValue();
console.log(value);
}
}function foo(bar) {
const result = 1;
if (bar) {
console.log(result);
}
}type Point = {x: number; y: number};
function createPoint() {
const point: Point = {x: 0, y: 0};
return point;
}function foo() {
while (condition) {
const value = getValue();
console.log(value);
}
}function foo() {
if (condition) {
const value = getValue();
console.log(value);
}
}Examples from the ESLint documentation.
unicorn/prefer-smaller-scope
eslint-plugin-unicorn
import unicorn from "eslint-plugin-unicorn";
export default [
{
plugins: { unicorn },
rules: {
"unicorn/prefer-smaller-scope": "error",
},
},
];Oxlint does not have this rule.
Biome does not have this rule.
Prefer a single object destructuring declaration per local const source.
Prefer .then().catch() over .then(…, …) for error handling.
Prefer simple conditions first in logical expressions.
Require type literals to be last in union types.
Require parentheses around complex spread arguments.