Loading

Quipoin Menu

Learn • Practice • Grow

Before ES6, JavaScript only had the var keyword for variable declarations. ES6 introduced let and const to improve scope management and prevent common bugs.

let and const are block scoped variables that help write safer and cleaner code.


Why let and const?

Problems with var:

  • Function-scoped, not block-scoped
  • Can be redeclared
  • Hoisting behavior can cause bugs
let and const solve these problems by:
  • Restricting scope to block {}
  • Preventing accidental redeclaration
  • Making code more predictable


let Keyword

Syntax

let variableName = value;


Example

let name = "Nikhil";
console.log(name); // Nikhil

name = "JavaScript";
console.log(name); // JavaScript


Key Point

  • let variables can be reassigned
  • let variables cannot be redeclared in the same scope
  • Block scoped: only exists inside { }


Example: Block Scope

if (true) {
    let age = 25;
    console.log(age); // 25
}
console.log(age); // ReferenceError: age is not defined

let variables are restricted to the block


Const Keyword

Syntax

const variableName = value;


Example

const pi = 3.14;
console.log(pi); // 3.14

pi = 3.14159; // Error: Assignment to constant variable


Key Point

  • cont variables cannot be reassigned
  • Must be initialized during declaration
  • Block scoped: only exists inside { }


Example: Object & Array with const

const prevents reassignment, not mutation.

const person = { name: "Nikhil" };
person.name = "JavaScript"; // ✅ Allowed
console.log(person.name); // JavaScript

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

  • You cannot reassign person or arr entirely
  • But you can modify their contents


Difference Between var, let and const

Featurevarletconst
ScopeFunctionBlockBlock
RedeclareYesNoNo
ReassignYesYesNo
HoistingYesYes (no init)Yes (no init)
Best UseLegacyMutable varsConstants / Immutable refs


When to Use

  • const - for constants, objects, arrays (when reference won’t change)
  • let - for loop counters, mutable variables
  • Avoid var in modern code


Two Minute Drill

  • let = block scoped, can reassign, cannot redeclare
  • const = block scoped, cannot reassign, prevents redeclaration
  • Objects / arrays declared with const can be mutated
  • Always prefer const for safer code
  • var is function scoped legacy, avoid in modern JS