# no-top-level-assignment-in-function

Rule `unicorn/no-top-level-assignment-in-function`. Disallow assigning to top-level variables from inside functions.

- Source: unicorn
- Technologies: JavaScript
- Kind: correctness
- Needs type information: no
- Autofix: no
- Reach: 9.5M weekly downloads of presets that enable it
- Trend: +30.3% last quarter
- Rank: #1123 by reach, #1142 by growth

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `unicorn/no-top-level-assignment-in-function` | no | no | package `eslint-plugin-unicorn` | [docs](https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v80.0.0/docs/rules/no-top-level-assignment-in-function.md) |

## Code examples

### Incorrect: the rule reports this

```js
let cache;

function build() {
  cache = new Map();
}
```

```js
let index = 0;

const next = () => index++;
```

### Correct: the rule accepts this

```js
function build() {
  const cache = new Map();
}
```

```js
const state = {
  index: 0,
};

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

Examples from the ESLint documentation.

## Enable it

### ESLint: `eslint.config.js`

```js
import unicorn from "eslint-plugin-unicorn";

export default [
  {
    plugins: { unicorn },
    rules: {
      "unicorn/no-top-level-assignment-in-function": "error",
    },
  },
];
```

## Presets that enable it

| Preset | Linter | Package | Rules | Weekly downloads | Trend |
| --- | --- | --- | --- | --- | --- |
| [Unicorn recommended](https://lintradar.dev/presets/unicorn-recommended.md) | ESLint | `eslint-plugin-unicorn` | 340 | 9.5M | +30.3% |

## Related rules

- [unicorn/no-unreadable-for-of-expression](https://lintradar.dev/rules/unicorn/no-unreadable-for-of-expression.md): Disallow unreadable iterable expressions in `for…of` and `for await…of` loop headers.
- [unicorn/no-unsafe-string-replacement](https://lintradar.dev/rules/unicorn/no-unsafe-string-replacement.md): Disallow non-literal replacement values in `String#replace()` and `String#replaceAll()`.
- [unicorn/no-this-outside-of-class](https://lintradar.dev/rules/unicorn/no-this-outside-of-class.md): Disallow `this` outside of classes.
- [unicorn/require-array-sort-compare](https://lintradar.dev/rules/unicorn/require-array-sort-compare.md): Require a compare function when calling `Array#sort()` or `Array#toSorted()`.
- [unicorn/no-useless-template-literals](https://lintradar.dev/rules/unicorn/no-useless-template-literals.md): Disallow useless template literal expressions.
- [unicorn/no-invalid-argument-count](https://lintradar.dev/rules/unicorn/no-invalid-argument-count.md): Disallow calling functions and constructors with an invalid number of arguments.

---

Web page: https://lintradar.dev/rules/unicorn/no-top-level-assignment-in-function. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
