# declarations-in-global-scope

Rule `sonarjs/declarations-in-global-scope`. Variables and functions should not be declared in the global scope

- Source: sonarjs
- Technologies: JavaScript
- Kind: style
- Needs type information: no
- Autofix: no
- Reach: 0 weekly downloads of presets that enable it
- Trend: 0% last quarter
- Rank: #2129 by reach

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `sonarjs/declarations-in-global-scope` | no | no | package `eslint-plugin-sonarjs` | [docs](https://rules.sonarsource.com/javascript/RSPEC-3798/) |

## Code examples

### Incorrect: the rule reports this

```js
var myVar = 42;       // Noncompliant
function myFunc() { } // Noncompliant
```

### Correct: the rule accepts this

```js
window.myVar = 42;
window.myFunc = function() { };
```

```js
let myVar = 42;
let myFunc = function() { }
```

```js
// IIFE
(function() {
  var myVar = 42;
  function myFunc() { }
})();
```

Examples from the ESLint documentation.

## Enable it

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

```js
export default [
  {
    rules: {
      "sonarjs/declarations-in-global-scope": "error",
    },
  },
];
```

## Related rules

- [sonarjs/cyclomatic-complexity](https://lintradar.dev/rules/sonarjs/cyclomatic-complexity.md): Cyclomatic Complexity of functions should not be too high
- [sonarjs/destructuring-assignment-syntax](https://lintradar.dev/rules/sonarjs/destructuring-assignment-syntax.md): Destructuring syntax should be used for assignments
- [sonarjs/elseif-without-else](https://lintradar.dev/rules/sonarjs/elseif-without-else.md): "if ... else if" constructs should end with "else" clauses
- [sonarjs/expression-complexity](https://lintradar.dev/rules/sonarjs/expression-complexity.md): Expressions should not be too complex
- [sonarjs/composite-assertions](https://lintradar.dev/rules/sonarjs/composite-assertions.md): Composite assertions should be split
- [sonarjs/file-header](https://lintradar.dev/rules/sonarjs/file-header.md): Track lack of copyright and license headers

---

Web page: https://lintradar.dev/rules/sonarjs/declarations-in-global-scope. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
