# block-scoped-var

Rule `sonarjs/block-scoped-var`. Variables should be used in the blocks where they are declared

- Source: sonarjs
- Technologies: JavaScript
- Kind: style
- Needs type information: no
- Autofix: no
- Reach: 6.2M weekly downloads of presets that enable it
- Trend: +62.1% last quarter
- Rank: #1188 by reach, #489 by growth

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `sonarjs/block-scoped-var` | yes | no | package `eslint-plugin-sonarjs` | [docs](https://rules.sonarsource.com/javascript/RSPEC-2392/) |

## Code examples

### Incorrect: the rule reports this

```js
function doSomething(a, b) {
  if (a > b) {
    var x = a - b;  // Noncompliant
  }

  if (a > 4) {
    console.log(x);
  }

  for (var i = 0; i < m; i++) { // Noncompliant, both loops use same variable
  }

  for (var i = 0; i < n; i++) {
  }

  return a + b;
}
```

### Correct: the rule accepts this

```js
function doSomething(a, b) {
  var x;

  if (a > b) {
    x = a - b;
  }

  if (a > 4) {
    console.log(x);
  }

  for (let i = 0; i < m; i++) {
  }

  for (let i = 0; i < n; i++) {
  }


  return a + b;
}
```

Examples from the ESLint documentation.

## Enable it

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

```js
export default [
  {
    rules: {
      "sonarjs/block-scoped-var": "error",
    },
  },
];
```

## Presets that enable it

| Preset | Linter | Package | Rules | Weekly downloads | Trend |
| --- | --- | --- | --- | --- | --- |
| [SonarJS recommended](https://lintradar.dev/presets/sonarjs-recommended.md) | ESLint | `eslint-plugin-sonarjs` | 230 | 6.2M | +62.1% |

## Related rules

- [eslint/block-scoped-var](https://lintradar.dev/rules/eslint/block-scoped-var.md): Enforce the use of variables within the scope they are defined
- [sonarjs/bitwise-operators](https://lintradar.dev/rules/sonarjs/bitwise-operators.md): Bitwise operators should not be used in boolean contexts
- [sonarjs/call-argument-line](https://lintradar.dev/rules/sonarjs/call-argument-line.md): Function call arguments should not start on new lines
- [sonarjs/aws-sqs-unencrypted-queue](https://lintradar.dev/rules/sonarjs/aws-sqs-unencrypted-queue.md): SQS queues should be encrypted
- [sonarjs/chai-determinate-assertion](https://lintradar.dev/rules/sonarjs/chai-determinate-assertion.md): Chai assertions should have only one reason to succeed
- [sonarjs/aws-sns-unencrypted-topics](https://lintradar.dev/rules/sonarjs/aws-sns-unencrypted-topics.md): Amazon SNS topics should be encrypted at rest

---

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