var, let, and const in JavaScript

🧩 1. var

  • Old way to declare variables (ES5 and earlier).
  • Function-scoped: Available throughout the function where it’s declared.
  • Hoisting: var declarations are hoisted to the top of their scope and initialized as undefined.
  • Can be redeclared and reassigned.

πŸ”Ή Example

function exampleVar() {
  console.log(a); // undefined (hoisted)
  var a = 10;
  console.log(a); // 10
}
exampleVar();
  • Inside a block (if, for), var ignores block scope:
if (true) {
  var x = 5;
}
console.log(x); // 5 β†’ accessible outside the block

🟒 2. let

  • Introduced in ES6.
  • Block-scoped: Exists only within {} where it’s declared.
  • Hoisting: Exists in β€œtemporal dead zone” until initialized β†’ accessing before declaration throws error.
  • Can be reassigned but cannot be redeclared in the same scope.

πŸ”Ή Example

let b = 10;
b = 20; // βœ… Reassignment allowed
// let b = 30; // ❌ Error: b already declared
  • Block scope:
if (true) {
  let y = 15;
  console.log(y); // 15
}
console.log(y); // ❌ Error: y is not defined outside block

πŸ”΅ 3. const

  • Also block-scoped.
  • Cannot be reassigned (constant reference).
  • Must be initialized at declaration.
  • For objects/arrays, the reference is constant, but contents can be modified.

πŸ”Ή Example

const c = 30;
// c = 40; // ❌ Error: Assignment to constant variable

const arr = [1, 2, 3];
arr.push(4); // βœ… Allowed, content changes
console.log(arr); // [1, 2, 3, 4]

const obj = { name: "Alice" };
obj.name = "Bob"; // βœ… Allowed, property changes

🟣 4. Comparison Table

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
Hoistingβœ… (initialized as undefined)βœ… (temporal dead zone)βœ… (temporal dead zone)
Redeclarationβœ… Allowed❌ Not allowed❌ Not allowed
Reassignmentβœ… Allowedβœ… Allowed❌ Not allowed (reference immutable)
Use CaseLegacy codeVariables that changeConstants or immutable references

⚑ 5. Hoisting Example

console.log(aVar);  // undefined
// console.log(aLet); // ❌ ReferenceError
// console.log(aConst); // ❌ ReferenceError

var aVar = 1;
let aLet = 2;
const aConst = 3;
  • var is hoisted with undefined.
  • let and const are hoisted but in temporal dead zone β†’ cannot be accessed before declaration.

🟀 6. Best Practices

  1. Avoid var in modern JS/TS.
  2. Use const by default, unless you need to reassign.
  3. Use let for variables that will change over time.
  4. Always respect block scope to prevent bugs.

πŸ”Ή Quick Rule of Thumb

const a = 10; // I will not reassign
let b = 20;   // I might reassign
// var c = 30; // Only if legacy code requires

Leave a Reply