# Variables: var, let, const

> What are the differences between var, let, and const in JavaScript, and when should you use each one?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-var-let-const
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What are the differences between var, let, and const in JavaScript, and when should you use each one?

## Answer

`var` is function-scoped, can be redeclared, and is hoisted with the value `undefined`. `let` and `const` (ES2015) are block-scoped and sit in the Temporal Dead Zone until their declaration runs; `let` can be reassigned while `const` cannot. The modern rule is simple: use `const` by default, `let` when the binding must change, and avoid `var`.

### Scope: function vs block

A block is anything between `{ }`: an `if`, a `for`, a `try`, or a bare block. `let` and `const` live only inside the block where they are declared. `var` ignores blocks and attaches to the nearest enclosing function, or to the global scope if there is none.

- A `var` declared inside an `if` is visible after the `if` ends, which leads to accidental leaks and name collisions.
- A top-level `var` in a classic browser script becomes a property of `window` (`window.count`). Top-level `let` and `const` do not.
- Inside ES modules everything is module-scoped anyway, but block scoping still applies within functions.

### Redeclaration, reassignment and hoisting

| Feature | `var` | `let` | `const` |
| --- | --- | --- | --- |
| Scope | Function | Block | Block |
| Redeclare in same scope | Allowed | SyntaxError | SyntaxError |
| Reassign | Allowed | Allowed | TypeError |
| Must initialise | No | No | Yes |
| Access before declaration | `undefined` | ReferenceError (TDZ) | ReferenceError (TDZ) |
| Creates `window` property at top level | Yes | No | No |

All three are hoisted in the sense that the engine knows about them before the code runs. The difference is initialisation: `var` starts as `undefined`, while `let` and `const` stay uninitialised until the declaration line executes. Touching them earlier throws `ReferenceError: Cannot access 'x' before initialization`. That window is the Temporal Dead Zone.

### const means a constant binding, not a frozen value

`const` stops you from pointing the name at something else. It does not make the value immutable. If the value is an object or array, you can still change its contents:

- `const cart = []; cart.push(item)` works.
- `cart = []` throws `TypeError: Assignment to constant variable.`
- To prevent mutation use `Object.freeze(cart)`, which is shallow, or keep data immutable by convention and create new objects with spread.

### The loop closure trap

The most common interview demo: closures created inside a `for (var i ...)` loop all see the same `i`, so they all print the final value. With `for (let i ...)` the spec creates a fresh binding for every iteration, so each closure captures its own value. This is why `setTimeout` inside a loop printed `3, 3, 3` in old code and `0, 1, 2` in modern code.

### What to use in real code

- `const` for almost everything: imported modules, functions, config objects, values computed once. It signals intent to readers and lets linters catch accidental reassignment.
- `let` for counters, accumulators, and values reassigned in branches.
- `var` only when maintaining legacy code. ESLint's `no-var` and `prefer-const` rules enforce this in most codebases, including Airbnb and the default TypeScript configs teams use.

**var vs let inside a loop. One shared i or one i per iteration. Switch the keyword under Tweak and replay.**

1. **var is function-scoped**: var i is hoisted once to the enclosing scope, so every iteration writes the same variable.
2. **let is block-scoped**: for (let i ...) creates a fresh binding of i for each iteration.
3. **Closures capture variables**: Arrows pushed in the loop keep a reference to whichever i they were created next to.
4. **Result**: With var every arrow returns the final value (3, 3, 3); with let they return 0, 1, 2.

## Code examples

### Function scope vs block scope

```
function scopeDemo() {
  if (true) {
    var a = 'var leaks out of the block';
    let b = 'let stays inside';
    const c = 'const stays inside';
  }
  console.log(a);
  console.log(typeof b); // typeof on an undeclared name is safe
  console.log(typeof c);
}
scopeDemo();
```

var attaches to the function, so it is visible after the if block. let and const are confined to the block where they were declared.

### Reassignment, redeclaration and const objects

```
var x = 1;
var x = 2;          // allowed, silently overwrites
let y = 1;
y = 2;              // allowed
// let y = 3;       // SyntaxError: Identifier 'y' has already been declared

const order = { id: 'ORD-101', amountPaise: 49900 };
order.amountPaise = 39900;   // allowed: mutating the object
// order = {};               // TypeError: Assignment to constant variable.

const frozen = Object.freeze({ status: 'PAID' });
frozen.status = 'REFUNDED';  // ignored (throws in strict mode)
console.log(x, y, order.amountPaise, frozen.status);
```

const protects the binding, not the object. Object.freeze makes the top-level properties read-only, but nested objects stay mutable.

### Closures in loops

```
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var:', i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log('let:', j), 0);
}
```

There is a single var i shared by all callbacks, and it is 3 by the time they run. let creates a new j per iteration, so each callback captures its own value.

## Key points

- var is function-scoped; let and const are block-scoped
- All three are hoisted, but let and const are uninitialised until declared (Temporal Dead Zone)
- const prevents reassignment, not mutation; use Object.freeze for shallow immutability
- let in a for loop creates a fresh binding per iteration, fixing the classic closure bug
- Top-level var in a script creates a property on window; let and const do not

## Common follow-up questions

- What is the Temporal Dead Zone and why does typeof throw inside it?
- How would you make a nested object truly immutable?
- Can you use const in a for...of loop? What about a classic for loop?
- What happens if you assign to an undeclared variable in sloppy mode vs strict mode?

## Interview tips

- Lead with scope (function vs block); it is the distinction interviewers care about most
- Show the setTimeout loop example unprompted; it proves you understand closures too
- Say clearly that const is not immutability, then mention Object.freeze being shallow

## Concepts covered

var, let, const, Block Scope, Function Scope, Temporal Dead Zone

Next: [Data Types & Type Checking](https://www.internhack.in/learn/interview/javascript-interview/js-data-types) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Operators & Short-Circuit Evaluation](https://www.internhack.in/learn/interview/javascript-interview/js-operators-short-circuit)
- [String Methods & Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-string-methods)
- [Array Methods (map, filter, reduce)](https://www.internhack.in/learn/interview/javascript-interview/js-array-methods)
- [Destructuring & Spread/Rest](https://www.internhack.in/learn/interview/javascript-interview/js-destructuring-spread)
- [Error Handling (try/catch/finally)](https://www.internhack.in/learn/interview/javascript-interview/js-error-handling)
- [== vs === Equality Operators](https://www.internhack.in/learn/interview/javascript-interview/js-equality-operators)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
