2️⃣ ✍️ TypeScript Syntax, Variables & Operators
Estimated reading: 4 minutes 282 views

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 let and const different from var
  • How variable scoping works in TypeScript
  • Why const is 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 age of type number and assigns it a value 30.
  • The variable age can be reassigned later if needed.
  • console.log(age); outputs 30 to 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 name of type string with 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

Featurevar (Legacy)let (Modern)const (Recommended)
ScopeFunctionBlockBlock
HoistingYes (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:

  • x is declared with var, so it’s accessible outside the if block — hence it prints 10.
  • y and z are block-scoped using let and const, so they can’t be accessed outside the if block, resulting in ReferenceError.

Example: Reassignment with let

let score = 50;
score = 75;
console.log(score); // 75

Explanation:

  • score is declared using let and 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:

  • maxScore is declared using const and set to 100.
  • Attempting to reassign it to 120 results 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 user is constant, but its properties are still mutable.
  • user.name is changed to "Doe" successfully.
  • console.log(user.name); prints "Doe".

Common Errors and Solutions

MistakeError MessageHow to Fix
Reassigning a const variableCannot assign to 'x' because it is a constantUse let instead of const
Accessing variable before declarationCannot access 'x' before initializationDeclare before using (avoid TDZ)
Redeclaring a let or const'x' has already been declaredRemove or rename the duplicate
Using var in modern codeUnexpected hoisting or scope issuesReplace with let or const

Best Practices for let and const

  • Use const by default unless you need reassignment
  • Use let when you expect to change the variable later
  • Avoid var in TypeScript — it’s outdated and error-prone
  • Always initialize const at 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:

  • let is block-scoped and allows reassignment
  • const is block-scoped and immutable (but objects can be modified)
  • Avoid var unless supporting legacy code
  • Always prefer const to 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 :
Share

TypeScript — let & const

Or Copy Link

CONTENTS
Scroll to Top