# Variable

> The Variable is a storage location identified by a name and used to store data that can change during the execution of a program.

## What is a variable in programming?

The named storage location used to hold data that can vary throughout the execution of a program. It can store values such as numbers, text or other data types.

- Topic: Basics
- Type: concept

## Example

Wrong:

```js
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
```

Right:

```js
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
```

`var` is function-scoped, so it logs 3, 3, 3; `let` creates a new binding per pass and logs 0, 1, 2.

## Common mistakes

- A `var` inside a loop is shared by every callback, so all of them see the last value.

## Key points

- New JavaScript code declares variables with `const` or `let`, not `var`.
- Variables have descriptive names, not `x`, `data2` or `temp`.
- Each variable is declared in the smallest scope that needs it.

## Interview questions

### What is the difference between a variable and a constant?

A variable can be reassigned while the program runs. A constant keeps the value it got first.

### Should I use let or const in JavaScript?

Use `const` by default and `let` only when the value must be reassigned.

## Related cards

- [Constant](https://wonderium.dev/engineering/constant.md)
- [let](https://wonderium.dev/js/let.md)
- [var](https://wonderium.dev/js/var.md)
- [Scope](https://wonderium.dev/js/scope.md)
- [Data Types](https://wonderium.dev/js/data-types.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/variable
- Last updated: 2026-11-25
