---
title: "vars-on-top"
description: "Require `var` declarations at the top of their function or file"
# Generated by src/codegen/lint-rule-docs.ts. Do not edit below this line.
plugin: "eslint"
aliases: ["eslint/vars-on-top"]
kind: "suggestion"
category: "style"
default: "off"
fixable: "no"
typeAware: false
deprecated: false
---

A `var` belongs to the whole function, no matter where it's written. Inside an `if` or a loop it looks local to that block, but it exists, as `undefined`, from the first line of the function. Writing every `var` at the top shows the scope the variable really has.

A `var` is at the top if only other variable declarations come before it. Directives such as `"use strict"` and `import` declarations may come first. A `var` in a block, or in a `for` loop's head, is always reported. `let` and `const` aren't checked.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"vars-on-top" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 2} */}
```js
function total(items) {
  var sum = 0;
  for (var i = 0; i < items.length; i++) {
    var price = items[i].price;
    sum += price;
  }
  return sum;
}
```

Not reported:

{/* good */}
```js
function total(items) {
  var sum = 0;
  var i;
  var price;
  for (i = 0; i < items.length; i++) {
    price = items[i].price;
    sum += price;
  }
  return sum;
}
```

## When not to use it

If your code uses `let` and `const`, which are scoped to their block, turn on `no-var` instead.
