🧰 TypeScript let & const – Modern Variable Declarations Explained with Examples
🧲 Introduction – Understanding let and const in TypeScript
In modern TypeScript development, using the right keyword to declare variables is critical for writing clean, maintainable, and bug-free code. let and const—both introduced with ES6—have replaced the older var due to their block-level scoping and improved safety features.
🎯 In this guide, you’ll explore:
- What makes letandconstdifferent fromvar
- How variable scoping works in TypeScript
- Why constis preferred in most situations
- Code examples with clear explanations
- Common errors and best practices
🔁 Declaring Variables with let in TypeScript
The let keyword allows you to declare variables that are block-scoped and reassignable.
📌 Syntax:
let age: number = 30;
console.log(age);
✅ Explanation:
- let age: number = 30;declares a variable- ageof type- numberand assigns it a value- 30.
- The variable agecan be reassigned later if needed.
- console.log(age);outputs- 30to the console.
🔒 Declaring Constants with const in TypeScript
const is used when the variable should never be reassigned after its initial value is set. It is also block-scoped like let.
📌 Syntax:
const name: string = "Alice";
console.log(name);
✅ Explanation:
- const name: string = "Alice";declares a constant named- nameof type- stringwith the value- "Alice".
- This value cannot be changed later in the code.
- console.log(name);prints- "Alice"to the console.
⚖️ let vs const vs var – Detailed Comparison Table
| Feature | var(Legacy) | let(Modern) | const(Recommended) | 
|---|---|---|---|
| Scope | Function | Block | Block | 
| Hoisting | Yes (but undefined) | Yes (TDZ applies) | Yes (TDZ applies) | 
| Reassignable | ✅ Yes | ✅ Yes | ❌ No | 
| Redeclarable | ✅ Yes | ❌ No | ❌ No | 
| Temporal Dead Zone | ❌ No | ✅ Yes | ✅ Yes | 
✅ Use const by default, switch to let only if you need reassignment. Avoid var for modern TypeScript.
🧠 Example: Block Scope Behavior
function testScope() {
    if (true) {
        var x = 10;
        let y = 20;
        const z = 30;
    }
    console.log(x); // 10
    console.log(y); // Error
    console.log(z); // Error
}
testScope();
✅ Explanation:
- xis declared with- var, so it’s accessible outside the- ifblock — hence it prints- 10.
- yand- zare block-scoped using- letand- const, so they can’t be accessed outside the- ifblock, resulting in ReferenceError.
🔁 Example: Reassignment with let
let score = 50;
score = 75;
console.log(score); // 75
✅ Explanation:
- scoreis declared using- letand initialized to- 50.
- It is reassigned to 75.
- console.log(score);prints- 75.
❌ Example: Reassignment with const (Invalid)
const maxScore = 100;
maxScore = 120; // ❌ Error
✅ Explanation:
- maxScoreis declared using- constand set to- 100.
- Attempting to reassign it to 120results in a TypeScript compile-time error: “Cannot assign to ‘maxScore’ because it is a constant.”
💡 Example: Mutating Objects with const
const user = { name: "John" };
user.name = "Doe";
console.log(user.name); // "Doe"
✅ Explanation:
- The object reference useris constant, but its properties are still mutable.
- user.nameis changed to- "Doe"successfully.
- console.log(user.name);prints- "Doe".
⚠️ Common Errors and Solutions
| Mistake | Error Message | How to Fix | 
|---|---|---|
| Reassigning a constvariable | Cannot assign to 'x' because it is a constant | Use letinstead ofconst | 
| Accessing variable before declaration | Cannot access 'x' before initialization | Declare before using (avoid TDZ) | 
| Redeclaring a letorconst | 'x' has already been declared | Remove or rename the duplicate | 
| Using varin modern code | Unexpected hoisting or scope issues | Replace with letorconst | 
🧑🏫 Best Practices for let and const
- ✅ Use constby default unless you need reassignment
- 🔁 Use letwhen you expect to change the variable later
- 🚫 Avoid varin TypeScript — it’s outdated and error-prone
- 🧼 Always initialize constat declaration
📌 Summary – Recap & Next Steps
By using let and const, you avoid the confusing scoping behaviors of var and gain the benefits of block-level scoping and immutability. This leads to more predictable, secure, and bug-resistant code in your TypeScript projects.
🔍 Key Takeaways:
- letis block-scoped and allows reassignment
- constis block-scoped and immutable (but objects can be modified)
- Avoid varunless supporting legacy code
- Always prefer constto prevent accidental reassignments
⚙️ Real-world relevance: Understanding how to declare variables properly is essential for writing clean functions, loop counters, and scoped variables in every TypeScript project.
❓ FAQs – let & const in TypeScript
❓ Can I use const for arrays or objects that I want to change?
✅ Yes. You cannot reassign the array or object reference, but you can change its contents.
const arr = [1, 2, 3];
arr.push(4); // ✅
arr = [5, 6]; // ❌ Error
❓ Why does TypeScript throw errors for variables declared with let or const before use?
✅ Due to the Temporal Dead Zone (TDZ)—accessing a variable before declaration results in a runtime error.
❓ Which is better for loops – let or const?
✅ Use let for loop counters since they change; use const for values that remain constant inside the loop.
❓ Can I declare multiple variables in one let or const?
✅ Yes, you can separate them with commas.
let x = 1, y = 2;
const a = 3, b = 4;
Share Now :
