Skip to content

Latest commit

Β 

History

History
48 lines (34 loc) Β· 1.31 KB

File metadata and controls

48 lines (34 loc) Β· 1.31 KB

no-top-level-assignment-in-function

πŸ“ Disallow assigning to top-level variables from inside functions.

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

Assigning to top-level variables from inside functions creates hidden shared state. A function can then change the result of later calls, or break when it becomes recursive, reentrant, or async.

Keep state local to the function, pass it explicitly, return it, or put intentional shared state in an object. If you truly need a module-level cache or other shared state, use an ESLint disable comment.

This rule only reports direct writes to top-level bindings. It ignores property mutations and variables from non-top-level outer scopes.

Examples

// ❌
let cache;

function build() {
	cache = new Map();
}
// βœ…
function build() {
	const cache = new Map();
}
// ❌
let index = 0;

const next = () => index++;
// βœ…
const state = {
	index: 0,
};

const next = () => state.index++;