# no-variable-usage-before-declaration

Rule `sonarjs/no-variable-usage-before-declaration`. Variables declared with "var" should be declared before they are used

- 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: #2168 by reach

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `sonarjs/no-variable-usage-before-declaration` | no | no | package `eslint-plugin-sonarjs` | [docs](https://rules.sonarsource.com/javascript/RSPEC-1526/) |

## Code examples

### Incorrect: the rule reports this

```js
var x = 1;

function fun(){
  alert(x); // Noncompliant as x is declared later in the same scope
  if(something) {
    var x = 42; // Declaration in function scope (not block scope!) shadows global variable
  }
}

fun(); // Unexpectedly alerts "undefined" instead of "1"
```

### Correct: the rule accepts this

```js
var x = 1;

function fun() {
  print(x);
  if (something) {
    x = 42;
  }
}

fun(); // Print "1"
```

Examples from the ESLint documentation.

## Enable it

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

```js
export default [
  {
    rules: {
      "sonarjs/no-variable-usage-before-declaration": "error",
    },
  },
];
```

## Related rules

- [sonarjs/no-unused-function-argument](https://lintradar.dev/rules/sonarjs/no-unused-function-argument.md): Unused function parameters should be removed
- [sonarjs/no-wildcard-import](https://lintradar.dev/rules/sonarjs/no-wildcard-import.md): Wildcard imports should not be used
- [sonarjs/non-number-in-arithmetic-expression](https://lintradar.dev/rules/sonarjs/non-number-in-arithmetic-expression.md): Arithmetic operators should only have numbers as operands
- [sonarjs/no-undefined-assignment](https://lintradar.dev/rules/sonarjs/no-undefined-assignment.md): "undefined" should not be assigned
- [sonarjs/operation-returning-nan](https://lintradar.dev/rules/sonarjs/operation-returning-nan.md): Arithmetic operations should not result in "NaN"
- [sonarjs/no-sonar-comments](https://lintradar.dev/rules/sonarjs/no-sonar-comments.md): Track uses of "NOSONAR" comments

---

Web page: https://lintradar.dev/rules/sonarjs/no-variable-usage-before-declaration. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
