let & const vs var

In JavaScript, let, const, and var are used to declare variables, but they behave differently in terms of scope, hoisting, and mutability.

Comparison of let, const, and var
Feature var let const
Scope Function-scoped Block-scoped Block-scoped
Hoisting Hoisted and initialized with undefined Hoisted but not initialized (Temporal Dead Zone) Hoisted but not initialized (Temporal Dead Zone)
Reassignment Allowed Allowed Not allowed
Redeclaration in same scope Allowed Not allowed Not allowed
Use case Legacy code or function scope variables Variables that will change Constants or variables that should not reassign
Illustration of let_const_vs_var
Illustration of let_const_vs_var

💡 Important

let and const were introduced in ES6 to address issues with var, mainly scoping and accidental redeclarations.

Scope Differences

var is function-scoped, meaning it is accessible throughout the function it is declared in, even before its declaration due to hoisting.

let and const are block-scoped, meaning they are only accessible within the nearest enclosing block (curly braces {}) where they are declared.

📌 Deep Dive: Scope Example

JAVASCRIPT
function testScope() {
  if (true) {
    var x = 1;
    let y = 2;
    const z = 3;
  }
  console.log(x); // 1  (function-scoped)
  console.log(y); // ReferenceError: y is not defined
  console.log(z); // ReferenceError: z is not defined
}
testScope();
Output
1
ReferenceError
ReferenceError

Hoisting Behavior

var declarations are hoisted and initialized with undefined, so you can access them before declaration (though it’s not recommended).

let and const are hoisted but not initialized, causing a "Temporal Dead Zone" until their declaration line is executed. Accessing them before declaration throws a ReferenceError.

📌 Deep Dive: Hoisting Example

JAVASCRIPT
// var example
console.log(a); // undefined
var a = 10;

// let example
console.log(b); // ReferenceError
let b = 20;

// const example
console.log(c); // ReferenceError
const c = 30;
Output
undefined
ReferenceError
ReferenceError

Mutability and Reassignment

var and let allow reassignment of the variable value.

const does not allow reassignment after initialization; the variable must be initialized when declared.

Note: const does not make objects or arrays immutable, only the binding cannot be changed.

📌 Deep Dive: Reassignment Example

JAVASCRIPT
// var and let reassignment
var x = 1;
x = 2; // allowed

let y = 3;
y = 4; // allowed

// const reassignment
const z = 5;
z = 6; // TypeError: Assignment to constant variable.

// const with objects
const obj = { prop: 1 };
obj.prop = 2; // allowed: object properties can change
Output
// No output for assignments
TypeError at z = 6
// No error for obj.prop = 2

⚠️ Common Pitfall

Using var can lead to bugs due to unexpected scope and hoisting. Prefer let and const for safer, clearer code.