JavaScript Variables: var vs let vs const

Feature var let const
Scope Function scoped Block scoped Block scoped
Re-assign ✅ Allowed ✅ Allowed ❌ Not allowed
Re-declare ✅ Allowed ❌ Not allowed ❌ Not allowed
Best Practice Avoid Good Best (default)
🔹 Re-assign: Existing value ko change karna.
🔹 Re-declare: Same variable ko dobara declare karna.
🔹 Scope: Variable ka accessible area (function ya block).

JavaScript: Var Features

Var = purana (old) way variable declare karne ka JavaScript me.

Variable = ek box jisme hum value store kar sakte hain (number, text, etc.)


1️⃣ Scope (Function / Block)

Var ka scope = Function scoped, block ignore karta hai

function scopeExample() {
    var x = 10;  // function ke andar declare
    console.log("Inside function x =", x);
}

scopeExample();

console.log("Outside function x =", typeof x); // undefined → function ke bahar access nahi

{
    var y = 50;  // var block ignore karta hai
    console.log("Inside block y =", y);
}

console.log("Outside block y =", y); // 50 → block ignore karta hai

2️⃣ Re-assign (Value Change)

Var me value change kar sakte ho

var a = 5;      
console.log("Before re-assign a =", a);  // 5

a = 15;         
console.log("After re-assign a =", a);   // 15

{
    var b = 20;
    console.log("Inside block b =", b);    // 20

    b = 30;
    console.log("After re-assign b =", b); // 30
}

console.log("Outside block b =", b);      // 30 → block ignore karta hai

3️⃣ Re-declare (Dobara Declare)

Var me same variable dobara declare kar sakte ho

var c = 100;
console.log("First declare c =", c);  // 100

var c = 200;  // Re-declare allowed
console.log("After re-declare c =", c); // 200

{
    var d = 300;
    console.log("Inside block first d =", d); // 300

    var d = 400; // Re-declare allowed
    console.log("Inside block after re-declare d =", d); // 400
}

console.log("Outside block d =", d); // 400 → block ignore karta hai

✅ Open browser console (F12 → Console) to see all outputs.