11001

What is the difference between `let`, `const`, and `var`?

var is function-scoped or globally-scoped and can be redeclared.

  • Creates property on window object.

  • Hoisted to top of its scope (either global or function scope) and initialized as undefined

  • Can be re-declared

function example() {
  var x = 1;
  if (true) {
    var x = 2; // Same variable!
    console.log(x); // 2
  }
  console.log(x); // 2 - leaked from block
}

There is two phases. Compilation phase (Hoisting happens) and Execution phase (Assignment happens)

console.log(x); // undefined (not ReferenceError)
var x = 5;

var name = "Alice";
var name = "Bob"; // No error

let and const are block-scoped. const cannot be reassigned after declaration, while let can be. const declaration requires value

const doesn't mean immutable value. Binding is constant, not the value

const config = { api: "v1" };
config.api = "v2"; // ✅ Allowed
Object.freeze(config); // Now truly immutable

const obj = { name: "Alice" };
obj.name = "Bob"; // ✅ Works - mutating object
obj.age = 30;     // ✅ Works - adding property
obj = {};         // ❌ TypeError - reassigning binding

const arr = [1, 2];
arr.push(3);      // ✅ Works - mutating array
arr = [];         // ❌ TypeError - reassigning

example with loops

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 (all reference same variable)

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Prints: 0, 1, 2 (each iteration gets own binding)