Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Variables: var, let, const

Variable declarations control scope, mutation, and runtime behavior. Most beginner and intermediate bugs in JavaScript are caused by incorrect variable usage.

Why this matters

Correct variable semantics reduce hidden bugs, avoid accidental global leaks, and make async behavior easier to reason about.

var, let, const: Practical Difference

var is function-scoped and can leak outside block boundaries, while let and const are block-scoped.

Use const as default. Switch to let only when reassignment is required. Avoid var in modern code unless working with legacy behavior.

These rules matter in loops, conditional branches, and closures where variable lifetime impacts output.

Hoisting and Temporal Dead Zone

All declarations are hoisted, but let and const remain inaccessible before declaration line. This period is called temporal dead zone.

Temporal dead zone prevents accidental usage before initialization and catches logic mistakes early.

Code Examples

Block Scope vs Function Scope

if (true) {
  var oldWay = "visible outside block";
  let modernWay = "only inside block";
}

console.log(oldWay); // works
// console.log(modernWay); // ReferenceError

var escapes block, let does not.

const with Object Mutation

const config = { mode: "light" };
config.mode = "dark"; // allowed
console.log(config.mode);

// config = {}; // TypeError

const locks binding, not nested object content.

Temporal Dead Zone

function demo() {
  // console.log(total); // ReferenceError
  let total = 10;
  console.log(total);
}
demo();

Accessing let/const before declaration throws runtime error.

Common Mistakes and Fixes

Using var in loops

Use let so each loop block has predictable scoped values.

Using let everywhere

Use const by default to prevent accidental reassignment.

Expecting const object immutability

Use Object.freeze or immutable update patterns for stricter guarantees.

Frequently Asked Questions

Which keyword should I use by default?

Use const by default and let when reassignment is required.

Why avoid var in modern JavaScript?

var has function scope and hoisting behavior that often causes confusing bugs.

What is temporal dead zone?

It is the time before let/const declaration where the variable exists but cannot be accessed.

Can const arrays be changed?

Array contents can be changed, but the variable cannot be reassigned to a new array.

Related JavaScript Topics