Understanding var, let, and const in JavaScript

What is a variable : A variable in JavaScript is a named memory location used to store data like numbers, strings, objects, arrays, etc., which can be accessed and modified later in the code.

🧠 What are they?

They are used to declare variables in JavaScript. But they behave differently in terms of scope, reassignment, and hoisting.

📦 var — The Old-School Way

function greet() {
  if (true) {
    var name = "John";
  }
  console.log(name); // ✅ Works
}
Re-declaration is allowed:
var a = 5;
var a = 10; // ✅ OK

📦 let — The Modern Way

function greet() {
  if (true) {
    let name = "Alice";
    console.log(name); // ✅ Works
  }
  // console.log(name); ❌ Error
}
Re-declaration is not allowed:
let x = 5;
x = 10;        // ✅ OK
let x = 20;    // ❌ Error

📦 const — Constant Value

const pi = 3.14;
console.log(pi); // ✅
// pi = 3.14159; ❌ Error
For arrays and objects:
const arr = [1, 2, 3];
arr.push(4);      // ✅

const person = { name: "Bob" };
person.name = "Tom"; // ✅

You can't reassign arr or person, but you can modify their content.

🧭 Scope Comparison Table

Feature var let const
Scope Function Block Block
Re-declarable ✅ Yes ❌ No ❌ No
Re-assignable ✅ Yes ✅ Yes ❌ No
Hoisting ✅ (undefined) ✅ (but not initialized) ✅ (but not initialized)

🎓 Real-World Analogy

Imagine a school:

Tips:
Use let when the value might change.
Use const for constants and object references.
Avoid var unless maintaining old code.