Understanding let and const in JavaScript
Everything you need to know in one place!
🌟 Introduction
In JavaScript, let and const are two modern ways to declare variables, introduced in ES6 (2015). They help us write cleaner and safer code compared to the old var.
🔍 What is let?
- Block scoped
- Can be updated
- Cannot be redeclared in the same scope
let count = 1;
count = 2; // ✅ Allowed
let count = 3; // ❌ SyntaxError (already declared in same scope)
🔒 What is const?
- Block scoped
- Cannot be updated or redeclared
- Must be initialized at the time of declaration
const name = 'Aman';
name = 'Rahul'; // ❌ TypeError (Assignment to constant variable)
📦 Scope Differences
Both let and const are block scoped, meaning they are only accessible within the enclosing { } block.
{
let x = 10;
const y = 20;
}
// console.log(x); // ❌ ReferenceError
// console.log(y); // ❌ ReferenceError
⚠️ Temporal Dead Zone
Using let or const before declaration causes a ReferenceError.
console.log(a); // ❌ ReferenceError
let a = 5;
✅ When to use what?
- Use
constby default - Use
letif the variable needs to change
Tags
_skills