# var

> The `var` JS syntax keyword declares a function-scoped or globally-scoped variable, depending on where it is used, hoisted to the top of its scope.

## Why should I not use var in JavaScript?

The keyword used to declare variables with function scope or global scope, depending on where it's used. Unlike `let` and `const`, which offer block scope, `var` allows redeclaration within the same function or global scope and can lead to unexpected behavior due to its function-wide hoisting.

- Topic: Syntax
- Type: syntax, keyword
- Browser support: Chrome 1+, Chrome Android 18+, Edge 12+, Firefox 1+, Firefox Android 4+, Safari 1+, Safari iOS 1+

## Example

Wrong:

```js
if (isAdmin) {
  var role = 'admin';
}
console.log(role); // 'admin' or undefined
```

Right:

```js
let role = 'user';
if (isAdmin) {
  role = 'admin';
}
console.log(role);
```

`var` ignores block boundaries; `let` keeps the variable where it is declared.

## Common mistakes

- Loop callbacks all seeing the final value of a `var` counter.
- A `var` inside an `if` block leaking into the whole function.

## Key points

- New code uses `const` or `let` instead of `var`.
- Refactors from `var` check that no code reads the variable before its line or outside its block.

## Interview questions

### Is var deprecated?

No. `var` still works and is not removed, but `let` and `const` are preferred for clearer scope.

### Can I redeclare a var variable?

Yes. `var` allows redeclaration in the same scope without an error, which can hide bugs.

## Related cards

- [let](https://wonderium.dev/js/let.md)
- [const](https://wonderium.dev/js/const.md)
- [Hoisting](https://wonderium.dev/js/hoisting.md)
- [Scope](https://wonderium.dev/js/scope.md)
- [Variables](https://wonderium.dev/js/variables.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/var
- Last updated: 2026-11-25
