HomeJAVASCRIPTVar vs let vs const in JavaScript

Var vs let vs const in JavaScript

🧠 Introduction:

“Hey developers! Today we’re diving deep into one of the most common JavaScript questions: What’s the difference between var, let, and const? Understanding these is crucial for writing modern, bug-free JavaScript. Let’s get into it!”

πŸ“Œ 1. var β€” The Old Way

  • Introduced in ES5 (before ES6).
  • Function-scoped, not block-scoped.
  • Can be re-declared and updated.
  • Gets hoisted to the top of its scope with undefined.
function test() {
  console.log(a); // undefined (due to hoisting)
  var a = 10;
  console.log(a); // 10
}
  • ❗ Downsides:
    • Can lead to bugs due to hoisting.
    • Scope leakage due to lack of block scoping.

πŸ†• 2. let β€” Modern and Safer

  • Introduced in ES6 (2015).
  • Block-scoped.
  • Can be updated, but not re-declared in the same scope.
  • Also hoisted, but not initialized.
function test() {
  // console.log(b); // ReferenceError
  let b = 20;
  console.log(b); // 20
}
  • βœ… Use let when you expect the value to change.

πŸ”’ 3. const β€” Immutable Binding

  • Also introduced in ES6.
  • Block-scoped like let.
  • Cannot be re-assigned or re-declared.
const c = 30;
// c = 40; // TypeError
  • ❗ However, objects declared with const are not immutable β€” just the binding is.
const obj = { name: 'Dev' };
obj.name = 'Coder'; // βœ… Allowed
  • βœ… Use const by default unless the variable needs to change.

πŸ†š Comparison Table

Featurevarletconst
ScopeFunction ScopeBlock ScopeBlock Scope
HoistingYes (undefined)Yes (TDZ*)Yes (TDZ*)
Re-declareYesNoNo
Re-assignYesYesNo
Temporal Dead Zone (TDZ)NoYesYes

TDZ (Temporal Dead Zone): Time between hoisting and declaration where the variable can’t be accessed.

Should I stop using var?

βœ… Yes, prefer let and const β€” they are block-scoped and safer.

When should I use let?

Use let when the variable’s value is expected to change.

When should I use const?

Use const when the variable will not be reassigned. This helps with code predictability.

Can const objects be mutated?

Yes, the reference is constant, not the object itself.

What happens if I access let or const before declaration?

You get a ReferenceError due to the Temporal Dead Zone.

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *