📌 Introduction

JavaScript has grown and improved over time. One of the biggest changes came with ES6 (ECMAScript 2015), which introduced two new ways of declaring variables: let and const. Before ES6, developers only used var. However, var often caused confusion because of its function scope and hoisting behavior. With the introduction of let and const, developers now have more predictable and safer options for declaring variables.

🔑 var

function demoVar() {
  console.log(a); // undefined (hoisted)
  var a = 10;
  console.log(a); // 10
}
demoVar();

⚠️ The problem with var is that in loops or asynchronous code, the variable does not stay where you expect it, which can create unexpected behavior.

🔑 let

function demoLet() {
  // console.log(b); // ❌ ReferenceError (TDZ)
  let b = 20;
  console.log(b); // 20
}
demoLet();

✅ Use let when the value of the variable needs to change later.

🔑 const

const c = 30;
console.log(c); // 30
// c = 40; // ❌ TypeError: Assignment to constant variable

⚡ But remember, if you use const with arrays or objects, you can still change the items inside them, because only the reference is constant, not the actual content:

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

🆚 var vs let vs const

Feature var let const
Scope Function-scoped Block-scoped Block-scoped
Hoisting Yes, initialized as undefined Yes, but TDZ applies Yes, but TDZ applies
Redeclaration Allowed Not allowed Not allowed
Reassignment Allowed Allowed Not allowed

Difference in table

📘 Best Practices

📝 Summary

In JavaScript, var, let, and const are used to declare variables, but they behave differently. var is function-scoped, hoisted, and can be redeclared, which often causes issues. let is block-scoped, cannot be redeclared, and should be used when the value may change. const is also block-scoped but cannot be reassigned, making it the best choice for values that should remain constant. By using let and const wisely, developers can write cleaner, safer, and more predictable code.